KeyedAsyncLock<TKey> Class

Provides an asynchronous lock mechanism that locks based on a key, allowing concurrent operations on different keys.

public sealed class KeyedAsyncLock<TKey> where TKey : notnull

Type parameters

TKey
The type of the key.

Example

var keyedLock = new KeyedAsyncLock<string>(StringComparer.Ordinal);
var updateCounts = new ConcurrentDictionary<string, int>(StringComparer.Ordinal);

async Task ProcessUserAsync(string userId)
{
    using (await keyedLock.LockAsync(userId))
    {
        // Only one operation per userId at a time
        // Multiple different userIds can be processed concurrently
        var count = updateCounts.GetValueOrDefault(userId);
        await Task.Yield();
        updateCounts[userId] = count + 1;
    }
}

await Task.WhenAll(ProcessUserAsync("alice"), ProcessUserAsync("alice"), ProcessUserAsync("bob"));
Assert.Equal(2, updateCounts["alice"]);
Assert.Equal(1, updateCounts["bob"]);

Nested types

NameDescription
KeyedAsyncLock<TKey>.KeyedAsyncLockLeaseRepresents a disposable lease for a KeyedAsyncLock<TKey>. Disposing the lease releases the lock for the key.

Constructors

NameDescription
KeyedAsyncLock()Initializes a new instance of the KeyedAsyncLock<TKey> class.
KeyedAsyncLock(IEqualityComparer<TKey>?)Initializes a new instance of the KeyedAsyncLock<TKey> class with the specified equality comparer.

KeyedAsyncLock overloads

KeyedAsyncLock()

KeyedAsyncLock.cs

Initializes a new instance of the KeyedAsyncLock<TKey> class.

public KeyedAsyncLock()

KeyedAsyncLock(IEqualityComparer<TKey>?)

KeyedAsyncLock.cs

Initializes a new instance of the KeyedAsyncLock<TKey> class with the specified equality comparer.

public KeyedAsyncLock(IEqualityComparer<TKey>? comparer)
Parameters
comparer IEqualityComparer<TKey>?
The equality comparer to use when comparing keys.

Methods

NameDescription
LockAsync(TKey, CancellationToken)Asynchronously acquires the lock for the specified key.

LockAsync(TKey, CancellationToken)

KeyedAsyncLock.cs

Asynchronously acquires the lock for the specified key.

public ValueTask<KeyedAsyncLock<TKey>.KeyedAsyncLockLease> LockAsync(TKey key, CancellationToken cancellationToken = default)

Parameters

key TKey
The key to lock on.
cancellationToken CancellationToken
A cancellation token to observe while waiting for the lock.

Returns

ValueTask<KeyedAsyncLock<TKey>.KeyedAsyncLockLease> A task that returns a disposable lease. Disposing the lease releases the lock.