C# System.Threading.Timer执行结束后再执行下个,通过异步锁 await async锁,lock,Monitor,SemaphoreSlim

异步方法内无法使用Monitor 和lock
所以只能用System.Threading.SemaphoreSlim了

//Semaphore (int initialCount, int maximumCount);
//initialCount代表还分配几个线程,比如是1,那就是还能允许一个线程继续跑锁起来的代码
//maximumCount代表最大允许数,比如是1,那就是进去1个线程,就会锁起来
System.Threading.SemaphoreSlim slimlock = new SemaphoreSlim(1, 1);       
var timerDeal = new Timer(async (t) => { await DealWork(); }, null, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(2));

private async Task DealWork()
{
     await slimlock.WaitAsync();
     try
     {
         //业务逻辑
         await Task.Delay(3000);
     }
     finally
     {
         slimlock.Release();
     }
}

而Monitor和lock只能用在非异步上面

static object locker = new object();
var timerDeal = new Timer((t) => { DoSometing(); }, null, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(2));

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);
         }
     }     
}

上述2两个加锁的例子完全是等价的,都是在非异步的时候锁定某段代码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值