-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAsyncKeyLock.cs
76 lines (63 loc) · 2.26 KB
/
AsyncKeyLock.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;
namespace RecNet.Common.Synchronization
{
/// <summary>
/// The <see cref="AsyncKeyLock{TKey}"/> provides the same locking semantics as <see cref="AsyncLock"/> but
/// dynamically scoped to caller provided keys. When multiple calls are made to lock the same key, then the
/// behavior is identical to <see cref="AsyncLock"/>. Calls made to lock different keys can all proceed
/// concurrently, allowing for high throughput.
/// </summary>
public class AsyncKeyLock<TKey> where TKey : notnull
{
#region Fields
private readonly RefCountedConcurrentDictionary<TKey, AsyncLock> _activeLocks;
private readonly ConcurrentBag<AsyncLock> _pool;
private readonly int _maxPoolSize;
#endregion
#region Constructor
public AsyncKeyLock(int maxPoolSize = 64)
{
_activeLocks = new RefCountedConcurrentDictionary<TKey, AsyncLock>(CreateLeasedLock, ReturnLeasedLock);
_pool = new ConcurrentBag<AsyncLock>();
_maxPoolSize = maxPoolSize;
}
#endregion
#region APIs
/// <summary>
/// Locks the current thread asynchronously.
/// </summary>
/// <param name="key">The key identifying the specific object to lock against.</param>
/// <returns>
/// The <see cref="Task{IDisposable}"/> that will release the lock.
/// </returns>
public Task<IDisposable> LockAsync(TKey key)
{
return _activeLocks.Get(key).LockAsync();
}
#endregion
#region RefCountedConcurrentDictionary Callbacks
private AsyncLock CreateLeasedLock(TKey key)
{
if (!_pool.TryTake(out AsyncLock? asyncLock))
{
asyncLock = new AsyncLock();
}
asyncLock.OnRelease = () => _activeLocks.Release(key);
return asyncLock;
}
private void ReturnLeasedLock(AsyncLock asyncLock)
{
if (_pool.Count < _maxPoolSize)
{
_pool.Add(asyncLock);
}
else
{
asyncLock.Dispose();
}
}
#endregion
}
}