AsyncLock 3.0 for .NET 5.0 Released

Safe, re-entrant locking in async contexts

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

If you would like to receive a notification the next time we release a nuget package for .NET or release resources for .NET Core and ASP.NET Core, you can subscribe below. Note that you'll only get notifications relevant to .NET programming and development by NeoSmart Technologies. If you want to receive email updates for all NeoSmart Technologies posts and releases, please sign up in the sidebar to the right instead.

  • Similar Posts

    Craving more? Here are some posts a vector similarity search turns up as being relevant or similar from our catalog you might also enjoy.
    1. AsyncLock: an async/await-friendly locking library for C# and .NET
  • Leave a Reply

    Your email address will not be published. Required fields are marked *