-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAsyncLock.cs
111 lines (90 loc) · 2.94 KB
/
AsyncLock.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
using System;
using System.Threading;
using System.Threading.Tasks;
namespace RecNet.Common.Synchronization
{
/// <summary>
/// An asynchronous locker that uses an IDisposable pattern for releasing the lock.
/// </summary>
public class AsyncLock : IDisposable
{
#region Types
private sealed class Releaser : IDisposable
{
private readonly AsyncLock _toRelease;
internal Releaser(AsyncLock toRelease) => _toRelease = toRelease;
public void Dispose() => _toRelease?.Release();
}
#endregion
#region Fields
private readonly SemaphoreSlim _semaphore;
#pragma warning disable IDE0069 // Disposable fields should be disposed
private readonly IDisposable _releaser;
#pragma warning restore IDE0069 // Disposable fields should be disposed
private readonly Task<IDisposable> _releaserTask;
private bool _disposed = false;
#endregion
#region Properties
/// <summary>
/// Gets or sets the callback that should be invoked whenever this lock is released.
/// </summary>
public Action? OnRelease { get; set; }
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="AsyncLock"/> class.
/// </summary>
public AsyncLock()
{
_semaphore = new SemaphoreSlim(1, 1);
_releaser = new Releaser(this);
_releaserTask = Task.FromResult(_releaser);
}
#endregion
#region APIs
/// <summary>
/// Asynchronously obtains the lock. Dispose the returned <see cref="IDisposable"/> to release the lock.
/// </summary>
/// <returns>
/// The <see cref="Task{IDisposable}"/> that will release the lock.
/// </returns>
public Task<IDisposable> LockAsync()
{
var wait = _semaphore.WaitAsync();
// No-allocation fast path when the semaphore wait completed synchronously
return (wait.Status == TaskStatus.RanToCompletion)
? _releaserTask
: AwaitThenReturn(wait, _releaser);
static async Task<IDisposable> AwaitThenReturn(Task t, IDisposable r)
{
await t;
return r;
}
}
private void Release()
{
try
{
_semaphore.Release();
}
finally
{
OnRelease?.Invoke();
}
}
#endregion
#region IDisposable
/// <summary>
/// Releases all resources used by the current instance of the <see cref="AsyncLock"/> class.
/// </summary>
public void Dispose()
{
if (!_disposed)
{
_semaphore.Dispose();
_disposed = true;
}
}
#endregion
}
}