AsyncLock Class
Provides an asynchronous lock that can be awaited to ensure exclusive access to a resource.
public sealed class AsyncLockExample
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
| Name | Description |
|---|---|
| AsyncLock.AsyncLockLease | Represents a disposable lease for an AsyncLock. Disposing the lease releases the lock. |
Constructors
| Name | Description |
|---|---|
| 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.csInitializes a new instance of the AsyncLock class.
public AsyncLock()AsyncLock(bool)
AsyncLock.csInitializes a new instance of the AsyncLock class with a Boolean value indicating whether to allow inlining of continuations.
public AsyncLock(bool allowInliningAwaiters)Parameters
allowInliningAwaitersbooltrueto allow continuations to be executed synchronously on the thread that releases the lock;falseto execute continuations asynchronously.
Methods
| Name | Description |
|---|---|
| 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.csAsynchronously 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.csAsynchronously acquires the lock.
public ValueTask<AsyncLock.AsyncLockLease> LockAsync(CancellationToken cancellationToken)Parameters
cancellationTokenCancellationToken- 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.csAttempts to acquire the lock synchronously without blocking.
public bool TryLock(out AsyncLock.AsyncLockLease lockObject)Parameters
lockObjectAsyncLock.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.