多线程定时器System.Timers.Timer

System.Timers.Timer是多线程定时器,如果一个Timer没有处理完成,到达下一个时间点,新的Timer同样会被启动,所以在使用Timer时需要注意。 
下面的实例显示了Timer的使用方法。

using System;
using System.Threading;
using System.Windows;

namespace TimerExp
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        System.Timers.Timer timer;
        public MainWindow()
        {
            InitializeComponent();
            if (timer == null)
            {
                timer = new System.Timers.Timer();
                timer.Interval = 1000;
                timer.Elapsed += timer_Elapsed;
            }
        }

        void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            Thread.Sleep(3000);
            string currentThreadId = Thread.CurrentThread.ManagedThreadId.ToString();
            this.Dispatcher.BeginInvoke(new Action(() =>
            {
                this.Label_Result.Content += currentThreadId + ",";
            }), null);
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            timer.Start();
        }
    }
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39

下图是实例的运行结果。 
这里写图片描述 
图中文本框显示的是运行定时器的当前线程ID。你会发现定时器会在不同的线程中运行。若将timer_Elapsed方法中让CPU休息3秒的代码去掉,你会发现这时定时器会在同一个线程中运行,为什么会这样呢?这是因为,实例中的Timer会每隔一秒钟执行一次timer_Elapsed方法,当前一次运行还没离开timer_Elapsed方法时,Timer便会在新的线程中运行timer_Elapsed方法,若前次运行已经离开timer_Elapsed方法,便会在同一个线程中继续运行timer_Elapsed方法。所以,Timer比较适合执行不太耗时的小任务,若在Timer中运行耗时任务,很容易出现由于超时导致的多线程重入问题,即多个线程同时进入timer_Elapsed方法。 
为了应对多线程重入问题。可以加锁,也可以增加标志位。 
下面的代码给出使用标志位的解决方案。

        int inTimer = 0;
        void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (Interlocked.Exchange(ref inTimer, 1) == 0)
            {
                Thread.Sleep(3000);
                string currentThreadId = Thread.CurrentThread.ManagedThreadId.ToString();
                this.Dispatcher.BeginInvoke(new Action(() =>
                {
                    this.Label_Result.Content += currentThreadId + ",";
                }), null);
                Interlocked.Exchange(ref inTimer, 0);
            }
        }
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

若使用”inTimer = 0”给变量inTimer直接赋值,在多线程环境中,同样有问题。Interlocked.Exchange提供了一种轻量级的线程安全的给对象赋值的方法,所以使用Interlocked.Exchange给变量赋值。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

苍狼_2001

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值