使用Nito.AsyncEx实现异步锁

时间:2023-03-09 02:49:23
使用Nito.AsyncEx实现异步锁

Lock是常用的同步锁,但是我们无法在Lock的内部实现异步调用,比如我们无法使用await.

以下面的代码为例,当你在lock内部使用await时,VS会报错提醒。

使用Nito.AsyncEx实现异步锁

最简单的解决办法就是使用第三方的库Nito.AsyncEx。可以通过Nuget安装。

使用Nito.AsyncEx实现异步锁

通过AsyncLock就可以在锁的内部实现异步操作了。

样例代码如下:

 public class AsyncLockDemo
{
//private readonly object _mutex = new object();
private readonly AsyncLock _mutex = new AsyncLock();
private int i = ;
public void Execute()
{
Console.WriteLine("before call foo1: "+ i); Foo1().ContinueWith(new Action<Task>(t =>
{
Console.WriteLine("foo1 completed: " + i);
})); Console.WriteLine("after call foo1: " + i); Console.WriteLine("before call foo2: " + i); Foo2().ContinueWith(new Action<Task>(t =>
{
Console.WriteLine("foo2 completed: " + i);
})); Console.WriteLine("after call foo2: " + i);
} public async Task Foo1()
{
using (await _mutex.LockAsync())
{
await Task.Delay(TimeSpan.FromSeconds());
Console.WriteLine("Foo1 start: " + i);
await DoSomethingAsync();
Console.WriteLine("Foo1 end: " + i);
}
} public async Task Foo2()
{
using (await _mutex.LockAsync())
{
Console.WriteLine("Foo2 start: " + i);
//await Task.Delay(TimeSpan.FromSeconds(1));
await DoSomethingAsync();
Console.WriteLine("Foo2 end: " + i);
}
} private Task DoSomethingAsync(int j)
{
return Task<string>.Run(() =>
{
Thread.Sleep();
i = j;
});
}
}

运行结果如下:

使用Nito.AsyncEx实现异步锁