-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAsyncMonitor.cs
More file actions
267 lines (238 loc) · 8.33 KB
/
Copy pathAsyncMonitor.cs
File metadata and controls
267 lines (238 loc) · 8.33 KB
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
// Copyright Subatomix Research Inc.
// SPDX-License-Identifier: MIT
namespace DependencyQueue;
using Void = ValueTuple;
/// <summary>
/// An exclusively lockable primitive, analogous to <see cref="Monitor"/>,
/// that supports both synchronous and asynchronous operations.
/// </summary>
internal class AsyncMonitor : IDisposable
{
// The exclusively lockable thing itself
private readonly SemaphoreSlim _locker;
// A fake task to implement pulse
private TaskCompletionSource<Void> _pulser;
/// <summary>
/// Initializes a new <see cref="AsyncMonitor"/> instance.
/// </summary>
internal AsyncMonitor()
{
_locker = new(initialCount: 1, maxCount: 1);
_pulser = null!; // to not pass uninitialized location to Volatile.Write
Volatile.Write(ref _pulser, new());
}
/// <summary>
/// Blocks the current thread until it acquires an exclusive lock on the
/// monitor.
/// </summary>
/// <returns>
/// A disposable object representing the lock held on the monitor.
/// Disposing the object releases the lock.
/// </returns>
/// <remarks>
/// This method is the equivalent of
/// <see cref="Monitor.Enter(object)"/>.
/// </remarks>
public Lock Acquire()
{
_locker.Wait();
return new(this);
}
/// <summary>
/// Waits asynchronously to acquire an exclusive lock on the monitor.
/// </summary>
/// <param name="cancellation">
/// The token to monitor for cancellation requests.
/// </param>
/// <returns>
/// A task that represents the asynchronous operation. When the task
/// completes, its <see cref="Task{T}.Result"/> is a disposable object
/// representing the lock held on the monitor. Disposing the object
/// releases the lock.
/// </returns>
/// <remarks>
/// This method is the asynchronous analog of
/// <see cref="Monitor.Enter(object)"/>.
/// </remarks>
public async Task<Lock> AcquireAsync(CancellationToken cancellation = default)
{
await _locker.WaitAsync(cancellation);
return new(this);
}
/// <summary>
/// Releases an exclusive lock on the monitor.
/// </summary>
/// <remarks>
/// <para>
/// ⚠ <strong>Warning:</strong>
/// This method must be called from a scope in which the current
/// thread holds an exclusive lock on the monitor.
/// </para>
/// <para>
/// This method is the equivalent of
/// <see cref="Monitor.Exit(object)"/>.
/// </para>
/// </remarks>
private void Release()
{
_locker.Release();
}
/// <summary>
/// Releases an exclusive lock on the monitor and blocks the current
/// thread until it reacquires the lock. Lock reacquisition begins
/// when signaled by <see cref="PulseAll"/> or when the specified
/// timeout elapses.
/// </summary>
/// <param name="timeoutMs">
/// The timeout interval in milliseconds.
/// </param>
/// <remarks>
/// <para>
/// ⚠ <strong>Warning:</strong>
/// This method must be called from a scope in which the current
/// thread holds an exclusive lock on the monitor.
/// </para>
/// <para>
/// This method is the equivalent of
/// <see cref="Monitor.Wait(object, int)"/>.
/// </para>
/// </remarks>
private void ReleaseUntilPulse(int timeoutMs)
{
var pulseTask = Volatile.Read(ref _pulser).Task;
var timeoutTask = Task.Delay(timeoutMs);
_locker.Release();
Task.WaitAny(pulseTask, timeoutTask);
_locker.Wait();
}
/// <summary>
/// Releases an exclusive lock on the monitor and waits asynchronously to
/// reacquire the lock. Lock reacquisition begins when signaled by
/// <see cref="PulseAll"/> or when the specified timeout elapses.
/// </summary>
/// <param name="timeoutMs">
/// The timeout interval in milliseconds.
/// </param>
/// <param name="cancellation">
/// The token to monitor for cancellation requests.
/// </param>
/// <returns>
/// A task that represents the asynchronous operation.
/// </returns>
/// <remarks>
/// <para>
/// ⚠ <strong>Warning:</strong>
/// This method must be called from a scope in which the current thread
/// holds an exclusive lock on the monitor.
/// </para>
/// <para>
/// This method is the asynchronous analog of
/// <see cref="Monitor.Wait(object, int)"/>.
/// </para>
/// </remarks>
private async Task ReleaseUntilPulseAsync(int timeoutMs, CancellationToken cancellation = default)
{
var pulseTask = Volatile.Read(ref _pulser).Task;
var timeoutTask = Task.Delay(timeoutMs, cancellation);
_locker.Release();
await Task.WhenAny(pulseTask, timeoutTask);
await _locker.WaitAsync(cancellation);
}
/// <summary>
/// Activates all execution contexts waiting for a pulse signal, so that
/// one of them can acquire an exclusive lock on the monitor.
/// </summary>
/// <remarks>
/// This method is the equivalent of
/// <see cref="Monitor.PulseAll(object)"/>.
/// </remarks>
public void PulseAll()
{
var signal = Interlocked.Exchange(ref _pulser, new());
signal.SetResult(default);
}
/// <summary>
/// Releases resources used by the monitor.
/// </summary>
/// <remarks>
/// ⚠ <strong>Warning:</strong>
/// This method is not thread-safe. Do not invoke this method
/// concurrently with other members of this instance.
/// </remarks>
public void Dispose()
{
Dispose(managed: true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases the unmanaged resources and, optionally, the managed
/// resources used by the monitor. Invoked by <see cref="Dispose()"/>.
/// Derived classes should override this method to extend disposal
/// behavior.
/// </summary>
/// <param name="managed">
/// <see langword="true"/>
/// to release both managed and unmanaged resources;
/// <see langword="false"/>
/// to release only unmanaged resources.
/// </param>
/// <remarks>
/// ⚠ <strong>Warning:</strong>
/// This method is not thread-safe. Do not invoke this method
/// concurrently with other members of this instance.
/// </remarks>
protected virtual void Dispose(bool managed)
{
if (!managed)
return;
_locker.Dispose();
}
/// <summary>
/// Represents an exclusive lock held against an
/// <see cref="AsyncMonitor"/>.
/// </summary>
internal class Lock : IDisposable
{
private const string TypeName
= nameof(AsyncMonitor) + "." + nameof(Lock);
private readonly AsyncMonitor _monitor;
private int _disposeCount;
internal Lock(AsyncMonitor monitor)
{
_monitor = monitor;
}
/// <inheritdoc cref="AsyncMonitor.ReleaseUntilPulse(int)"/>
public void ReleaseUntilPulse(int timeoutMs)
{
RequireNotDisposed();
_monitor.ReleaseUntilPulse(timeoutMs);
}
/// <inheritdoc cref="AsyncMonitor.ReleaseUntilPulseAsync(int, CancellationToken)"/>
public Task ReleaseUntilPulseAsync(int timeoutMs, CancellationToken cancellation = default)
{
RequireNotDisposed();
return _monitor.ReleaseUntilPulseAsync(timeoutMs, cancellation);
}
/// <summary>
/// Throws an <see cref="ObjectDisposedException"/> if the object is
/// disposed. Otherwise, this method does nothing.
/// </summary>
public void RequireNotDisposed()
{
if (_disposeCount != 0)
throw Errors.ObjectDisposed(TypeName);
}
/// <summary>
/// Releases the exclusive lock.
/// </summary>
/// <remarks>
/// It is safe to invoke this method multiple times. Only the first
/// invocation has an effect.
/// </remarks>
public void Dispose()
{
if (Interlocked.Exchange(ref _disposeCount, 1) == 0)
_monitor.Release();
}
}
}