An updated version of AsyncLock
has just been released on GitHub and Nuget with improved support for reentrancy detection.
AsyncLock
is a async/await-native anonymous lock for .NET and .NET Core that allows safely using async/await while holding a lock, for example:
class AsyncLockTest
{
AsyncLock _lock = new AsyncLock();
void Test()
{
// The code below will be run immediately and asynchronously.
// It *may* be run in a new thread, but we can't know.
Task.Run(async () => {
// This first LockAsync() call should not block
using (await _lock.LockAsync())
{
// This second call to LockAsync() will be recognized
// as being a reëntrant call and go through
using (await _lock.LockAsync())
{
// We now hold the lock exclusively and no one else
// can use it for 1 minute
await Task.Delay(TimeSpan.FromMinutes(1));
}
}
}).Wait(TimeSpan.FromSeconds(30));
// This call to obtain the lock is synchronously made from the main
// thread. It will, however, block until the asynchronous code which
// obtained the lock above finishes
using (_lock.Lock())
{
// We have now obtained exclusive access
}
}
}
Refer to the original article covering async locking for more information.
You can install AsyncLock
via the dotnet
or nuget
command line applications:
dotnet add reference NeoSmart.AsyncLock
Is it possible to use this with .net framework 4.x?
@desjardins: yes