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 : notnullType 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
| Name | Description |
|---|---|
| KeyedAsyncLock<TKey>.KeyedAsyncLockLease | Represents a disposable lease for a KeyedAsyncLock<TKey>. Disposing the lease releases the lock for the key. |
Constructors
| Name | Description |
|---|---|
| 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.csInitializes a new instance of the KeyedAsyncLock<TKey> class.
public KeyedAsyncLock()KeyedAsyncLock(IEqualityComparer<TKey>?)
KeyedAsyncLock.csInitializes a new instance of the KeyedAsyncLock<TKey> class with the specified equality comparer.
public KeyedAsyncLock(IEqualityComparer<TKey>? comparer)Parameters
comparerIEqualityComparer<TKey>?- The equality comparer to use when comparing keys.
Methods
| Name | Description |
|---|---|
| LockAsync(TKey, CancellationToken) | Asynchronously acquires the lock for the specified key. |
LockAsync(TKey, CancellationToken)
KeyedAsyncLock.csAsynchronously acquires the lock for the specified key.
public ValueTask<KeyedAsyncLock<TKey>.KeyedAsyncLockLease> LockAsync(TKey key, CancellationToken cancellationToken = default)Parameters
keyTKey- The key to lock on.
cancellationTokenCancellationToken- 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.