C#中Timer定时器,保证上一个任务执行完成了,才能执行下一个任务。

这个博客介绍了如何使用C#的System.Timers.Timer实现一个每30秒触发一次的任务执行器。任务执行过程中采用了锁(Monitor.TryEnter/Exit)来确保在多线程环境下,上一个任务完成后再执行下一个任务,从而保证任务的串行执行和顺序正确。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 相关代码如下:


        public class  Tasker {
        System.Timers.Timer timer = new System.Timers.Timer();
        static object locker = new object();

        public Tasker()
        {
            timer.Interval =30000;
            timer.Start();
            timer.Elapsed += new System.Timers.ElapsedEventHandler(DoSometing);
            Console.WriteLine("OK, timer start at: " + DateTime.Now.ToString());
        }

      
        private void DoSometing(object source, ElapsedEventArgs e)
        {
            if (Monitor.TryEnter(locker))
            {
                ///队列中的上一个任务执行完了,才能执行下一个任务
                ///保证上一个任务执行完了。
                try
                {
                    // my processing code
                    Console.WriteLine("process ...." + DateTime.Now.ToString());
                }
                finally
                {
                    Monitor.Exit(locker);
                }
            }
         
        }

        
  }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值