Thread Safe Async Locking
The lock(variable)
method is not compatible with async
await
calls
lock(padlock)
{
// This won't work
await ComputeAsync(padlock);
}
So instead you need to use the SemaphoreSlim class with a value parameter of 1 to implement the same behaviour:
var semaphore = new SemaphoreSlim(1);
await DoWorkAsync(123);
...
async Task DoWorkAsync(int value)
{
semaphore.WaitAsync();
try
{
await ComputeAsync(value);
}
finally
{
semaphore.Release();
}
}
The parameter value of 1 we used sets the count such that only one thread can access that code at a time.
Also call the release in a finally block to ensure the release code is called no matter if something happens, and thus avoid a potential deadlock.