You can use SemaphoreSlim
to act as an async
-compatible lock:
SemaphoreSlim _mutex = new SemaphoreSlim(1);
async Task MyMethodAsync()
{
await _mutex.WaitAsync();
try
{
...
}
finally
{
_mutex.Release();
}
}
Personally, I don't like the finally
, so I usually write my own IDisposable
to release the mutex when disposed, and my code can look like this:
async Task MyMethodAsync()
{
// LockAsync is an extension method returning my custom IDisposable
using (await _mutex.LockAsync())
{
...
}
}