NeoSmart.AsyncLock 3.2.1 The ID prefix of this package has been reserved for one of the owners of this package by NuGet.org. Prefix Reserved

.NET 5.0 .NET Standard 1.3
Install-Package NeoSmart.AsyncLock -Version 3.2.1
dotnet add package NeoSmart.AsyncLock --version 3.2.1
<PackageReference Include="NeoSmart.AsyncLock" Version="3.2.1" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add NeoSmart.AsyncLock --version 3.2.1
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
#r "nuget: NeoSmart.AsyncLock, 3.2.1"
#r directive can be used in F# Interactive, C# scripting and .NET Interactive. Copy this into the interactive tool or source code of the script to reference the package.
// Install NeoSmart.AsyncLock as a Cake Addin
#addin nuget:?package=NeoSmart.AsyncLock&version=3.2.1

// Install NeoSmart.AsyncLock as a Cake Tool
#tool nuget:?package=NeoSmart.AsyncLock&version=3.2.1
The NuGet Team does not provide support for this client. Please contact its maintainers for support.

AsyncLock: An async/await-friendly lock

AsyncLock is an async/await-friendly lock implementation for .NET Standard, making writing code like the snippet below (mostly) possible:

lock (_lockObject)
{
    await DoSomething();
}

Unlike most other so-called "async locks" for C#, AsyncLock is actually designed to support the programming paradigm lock encourages, not just the technical elements. You can read more about the pitfalls with other so-called asynchronous locks and the difficulties of creating a reentrance-safe implementation here.

With AsyncLock, you don't have to worry about which thread is running what code in order to determine whether or not your locks will have any effect or if they'll be bypassed completely, you just write code the way you normally would and you'll find AsyncLock to correctly marshal access to protected code segments.

Using AsyncLock

There are only three functions to familiarize yourself with: the AsyncLock() constructor and the two locking variants Lock()/LockAsync() .

AsyncLock() creates a new asynchronous lock. A separate AsyncLock should be used for each "critical operation" you will be performing. (Or you can use a global lock just like some people still insist on using global mutexes and semaphores. We won't judge too harshly.)

Everywhere you would normally use lock (_lockObject) you will now use one of

  • using (_lock.Lock()) or
  • using (await _lock.LockAsync())

That's all there is to it!

Async-friendly locking by design

Much like theSemaphoreSlim class, AsyncLock offers two different "wait" options, a blocking Lock() call and the asynchronous LockAsync() call. The utmost scare should be taken to never call LockAsync() without an await before it, for obvious reasons.

Upon using LockAsync(), AsyncLock will attempt to obtain exclusive access to the lock. Should that not be possible in the current state, it will cede its execution slot and return to the caller, allowing the system to marshal resources efficiently as needed without blocking until the lock becomes available. Once the lock is available, the AsyncLock() call will resume, transferring execution to the protected section of the code.

AsyncLock usage example

private class AsyncLockTest
{
    var _lock = new AsyncLock();

    void Test()
    {
        // The code below will be run immediately (likely in a new thread)
        Task.Run(async () =>
             {
                 // A first call to LockAsync() will obtain the lock without blocking
                 using (await _lock.LockAsync())
                 {
                     // A second call to LockAsync() will be recognized as being
                     // reentrant and permitted to go through without blocking.
                     using (await _lock.LockAsync())
                     {
                         // We now exclusively hold the lock for 1 minute
                         await Task.Delay(TimeSpan.FromMinutes(1));
                     }
                 }
             }).Wait(TimeSpan.FromSeconds(30));

        // This call to obtain the lock is made synchronously from the main thread.
        // It will, however, block until the asynchronous code which obtained the lock
        // above finishes.
        using (_lock.Lock())
        {
            // Now we have obtained exclusive access.
            // <Safely perform non-thread-safe operation safely here>
        }
    }
}
Product Versions
.NET net5.0 net5.0-windows net6.0 net6.0-android net6.0-ios net6.0-maccatalyst net6.0-macos net6.0-tvos net6.0-windows
.NET Core netcoreapp1.0 netcoreapp1.1 netcoreapp2.0 netcoreapp2.1 netcoreapp2.2 netcoreapp3.0 netcoreapp3.1
.NET Standard netstandard1.3 netstandard1.4 netstandard1.5 netstandard1.6 netstandard2.0 netstandard2.1
.NET Framework net46 net461 net462 net463 net47 net471 net472 net48
MonoAndroid monoandroid
MonoMac monomac
MonoTouch monotouch
Tizen tizen30 tizen40 tizen60
Universal Windows Platform uap uap10.0
Xamarin.iOS xamarinios
Xamarin.Mac xamarinmac
Xamarin.TVOS xamarintvos
Xamarin.WatchOS xamarinwatchos
Compatible target framework(s)
Additional computed target framework(s)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (19)

Showing the top 5 NuGet packages that depend on NeoSmart.AsyncLock:

Package Downloads
ZayniFramework.Common

Common used C# .NET libraries such as configuration management, extensions API, dynamic object libraries API, reflection libraries, AOP interceptors, delegate invokers, TaskQueue, AsyncWorker... etc. It also provides common used IResult interface, dynamic BaseResult class and built-in ConsoleCommandService with ICommand interface. GitLab Repository: https://gitlab.com/ponylin1985/ZayniFramework

EventDriven.EventBus.Dapr

An event bus abstraction layer over Dapr pub/sub.

EventDriven.EventBus.Abstractions

An event bus abstraction layer.

Super.Utils

Package Description

IRO.Storage

Simple key-value storage for client applications.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
3.2.1 15,334 1/10/2022
3.2.0 3,072 12/15/2021
3.2.0-preview2 458 10/29/2021
3.2.0-preview1 164 10/18/2021
3.1.0 32,637 4/29/2021
3.1.0-BETA1 221 2/17/2021
3.0.1 20,337 12/18/2020
3.0.0 379 12/15/2020
0.3.0.2 284,942 5/17/2017
0.3.0.1 695 5/17/2017
0.3.0 688 5/17/2017
0.2.0 671 5/16/2017
0.1.0 715 5/14/2017

3.2: New TryLock() and TryLockAsync() methods, CancellationToken support for synchronous locking routines.

3.0: Smarter method of detecting recursion for faster and more-reliable locking on all platforms.

3.1: Added synchronous locking that may be intermixed with async locking.

3.2: Added TryLock() and TryLockAsync() methods.