-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAsyncKeyReaderWriterLock.cs
84 lines (70 loc) · 2.81 KB
/
AsyncKeyReaderWriterLock.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
77
78
79
80
81
82
83
84
using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;
namespace RecNet.Common.Synchronization
{
/// <summary>
/// The <see cref="AsyncKeyReaderWriterLock{TKey}"/> provides the same locking semantics as
/// <see cref="AsyncReaderWriterLock"/> 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="AsyncReaderWriterLock"/>.
/// Calls made to lock different keys can all proceed concurrently, allowing for high throughput.
/// </summary>
public class AsyncKeyReaderWriterLock<TKey> where TKey : notnull
{
#region Fields
private readonly RefCountedConcurrentDictionary<TKey, AsyncReaderWriterLock> _activeLocks;
private readonly ConcurrentBag<AsyncReaderWriterLock> _pool;
private readonly int _maxPoolSize;
#endregion
#region Constructors
public AsyncKeyReaderWriterLock(int maxPoolSize = 64)
{
_activeLocks = new RefCountedConcurrentDictionary<TKey, AsyncReaderWriterLock>(CreateLeasedLock, ReturnLeasedLock);
_pool = new ConcurrentBag<AsyncReaderWriterLock>();
_maxPoolSize = maxPoolSize;
}
#endregion
#region APIs
/// <summary>
/// Locks the current thread in read mode 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> ReaderLockAsync(TKey key)
{
return _activeLocks.Get(key).ReaderLockAsync();
}
/// <summary>
/// Locks the current thread in write mode 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> WriterLockAsync(TKey key)
{
return _activeLocks.Get(key).WriterLockAsync();
}
#endregion
#region RefCountedConcurrentDictionary Callbacks
private AsyncReaderWriterLock CreateLeasedLock(TKey key)
{
if (!_pool.TryTake(out AsyncReaderWriterLock? asyncLock))
{
asyncLock = new AsyncReaderWriterLock();
}
asyncLock.OnRelease = () => _activeLocks.Release(key);
return asyncLock;
}
private void ReturnLeasedLock(AsyncReaderWriterLock asyncLock)
{
if (_pool.Count < _maxPoolSize)
{
_pool.Add(asyncLock);
}
}
#endregion
}
}