AsyncLock Class

Provides an asynchronous lock that can be awaited to ensure exclusive access to a resource.

public sealed class AsyncLock

Example

var asyncLock = new AsyncLock();
var counter = 0;

async Task AccessResourceAsync()
{
    using (await asyncLock.LockAsync())
    {
        // Critical section - only one task can execute this at a time
        var value = counter;
        await Task.Yield();
        counter = value + 1;
    }
}

await Task.WhenAll(AccessResourceAsync(), AccessResourceAsync(), AccessResourceAsync());
Assert.Equal(3, counter);

Nested types

NameDescription
AsyncLock.AsyncLockLeaseRepresents a disposable lease for an AsyncLock. Disposing the lease releases the lock.

Constructors

NameDescription
AsyncLock()Initializes a new instance of the AsyncLock class.
AsyncLock(bool)Initializes a new instance of the AsyncLock class with a Boolean value indicating whether to allow inlining of continuations.

AsyncLock overloads

AsyncLock()

AsyncLock.cs

Initializes a new instance of the AsyncLock class.

public AsyncLock()

AsyncLock(bool)

AsyncLock.cs

Initializes a new instance of the AsyncLock class with a Boolean value indicating whether to allow inlining of continuations.

public AsyncLock(bool allowInliningAwaiters)
Parameters
allowInliningAwaiters bool
true to allow continuations to be executed synchronously on the thread that releases the lock; false to execute continuations asynchronously.

Methods

NameDescription
LockAsync()Asynchronously acquires the lock.
LockAsync(CancellationToken)Asynchronously acquires the lock.
TryLock(AsyncLock.AsyncLockLease)Attempts to acquire the lock synchronously without blocking.

LockAsync overloads

LockAsync()

AsyncLock.cs

Asynchronously acquires the lock.

public ValueTask<AsyncLock.AsyncLockLease> LockAsync()
Returns

ValueTask<AsyncLock.AsyncLockLease> A task that returns a disposable lease. Disposing the lease releases the lock.

LockAsync(CancellationToken)

AsyncLock.cs

Asynchronously acquires the lock.

public ValueTask<AsyncLock.AsyncLockLease> LockAsync(CancellationToken cancellationToken)
Parameters
cancellationToken CancellationToken
A cancellation token to observe while waiting for the lock.
Returns

ValueTask<AsyncLock.AsyncLockLease> A task that returns a disposable lease. Disposing the lease releases the lock.

TryLock(AsyncLock.AsyncLockLease)

AsyncLock.cs

Attempts to acquire the lock synchronously without blocking.

public bool TryLock(out AsyncLock.AsyncLockLease lockObject)

Parameters

lockObject AsyncLock.AsyncLockLease
When this method returns, contains a disposable lease if the lock was acquired; otherwise, an empty lease.

Returns

bool true if the lock was acquired; otherwise, false.