异步方法内无法使用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两个加锁的例子完全是等价的,都是在非异步的时候锁定某段代码