-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathAsyncLock.cs
More file actions
366 lines (335 loc) · 17.5 KB
/
AsyncLock.cs
File metadata and controls
366 lines (335 loc) · 17.5 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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
using System;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
namespace CK.Core;
/// <summary>
/// Asynchronous/synchronous lock with recursion support based on a <see cref="SemaphoreSlim"/>.
/// Recursion support relies on the <see cref="IActivityMonitor"/> that is a required parameter
/// of all the methods: it is this monitor that acts as the "acquisition context".
/// </summary>
/// <remarks>
/// This lock is not disposable and this is intentional because unnecessary: a SemaphoreSlim must be
/// disposed only if its <see cref="SemaphoreSlim.AvailableWaitHandle"/> has been used and since we
/// encapsulate the semaphore and don't use it, we can avoid the IDisposable burden.
/// </remarks>
public sealed class AsyncLock
{
/// <summary>
/// The gate that controls logging for AsyncLock. Can be reused by other async related
/// features. It is closed by default.
/// </summary>
public static readonly StaticGate Gate = new StaticGate( nameof( AsyncLock ), false );
readonly SemaphoreSlim _semaphore;
readonly LockRecursionPolicy _policy;
IActivityMonitorOutput? _current;
int _recCount;
readonly string _name;
/// <summary>
/// Initializes a new lock with an explicit name.
/// </summary>
/// <param name="recursionPolicy">the recursion policy to use.</param>
/// <param name="name">A name for this lock.</param>
public AsyncLock( LockRecursionPolicy recursionPolicy, string name )
{
_semaphore = new SemaphoreSlim( 1, 1 );
_policy = recursionPolicy;
_name = name;
}
/// <summary>
/// Initializes a new lock with an automatic name (source file and line number).
/// </summary>
/// <param name="recursionPolicy">the recursion policy to use.</param>
/// <param name="filePath">The path of the file that instantiates this lock. Automatically set by the compiler.</param>
/// <param name="lineNmber">The line number in the source file where this lock has been instantiated. Automatically set by the compiler.</param>
public AsyncLock( LockRecursionPolicy recursionPolicy, [CallerFilePath] string? filePath = null, [CallerLineNumber] int lineNmber = 0 )
{
_semaphore = new SemaphoreSlim( initialCount: 1, maxCount: 1 );
_policy = recursionPolicy;
_name = $"{filePath}@{lineNmber}";
}
/// <summary>
/// Gets the name of this lock.
/// </summary>
public string Name => _name;
/// <summary>
/// Helper to support using statement.
/// <see cref="Enter(IActivityMonitor)"/> this lock and returns a <see cref="IDisposable"/> that will <see cref="Leave(IActivityMonitor)"/> this lock.
/// </summary>
/// <param name="monitor">The monitor that identifies the activity.</param>
/// <returns>The disposable to release the lock.</returns>
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public Releaser Lock( IActivityMonitor monitor )
{
Enter( monitor );
return new Releaser( this, monitor );
}
/// <summary>
/// Helper to support using statement.
/// <see cref="Enter(IActivityMonitor)"/> this lock and returns a <see cref="IDisposable"/> that will <see cref="Leave(IActivityMonitor)"/> this lock.
/// </summary>
/// <param name="monitor">The monitor that identifies the activity.</param>
/// <param name="cancel">Cancellation token.</param>
/// <returns>The disposable to release the lock.</returns>
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public Releaser Lock( IActivityMonitor monitor, CancellationToken cancel )
{
Enter( monitor, cancel );
return new Releaser( this, monitor );
}
/// <summary>
/// Helper to support using statement.
/// <see cref="EnterAsync(IActivityMonitor)"/> this lock and returns an awaitable <see cref="IDisposable"/> that
/// will <see cref="Leave(IActivityMonitor)"/> this lock.
/// <para>
/// This returns a ValueTask (that is not IDisposable): forgetting the await in the <c>using( await _lock.LockAsync() )</c> is not possible
/// since this doesn't compile.
/// </para>
/// </summary>
/// <param name="monitor">The monitor that identifies the activity.</param>
/// <returns>The disposable to release the lock.</returns>
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public ValueTask<Releaser> LockAsync( IActivityMonitor monitor ) => new ValueTask<Releaser>( DoLockAsync( monitor, CancellationToken.None ) );
/// <summary>
/// Helper to support using statement.
/// <see cref="EnterAsync(IActivityMonitor,CancellationToken)"/> this lock and returns an awaitable <see cref="IDisposable"/> that
/// will <see cref="Leave(IActivityMonitor)"/> this lock.
/// <para>
/// This returns a ValueTask (that is not IDisposable): forgetting the await in the <c>using( await _lock.LockAsync() )</c> is not possible
/// since this doesn't compile.
/// </para>
/// </summary>
/// <param name="monitor">The monitor that identifies the activity.</param>
/// <param name="cancel">Cancellation token.</param>
/// <returns>The disposable to release the lock.</returns>
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public ValueTask<Releaser> LockAsync( IActivityMonitor monitor, CancellationToken cancel ) => new ValueTask<Releaser>( DoLockAsync( monitor, cancel ) );
async Task<Releaser> DoLockAsync( IActivityMonitor monitor, CancellationToken cancel )
{
await EnterAsync( monitor, Timeout.Infinite, cancel );
return new Releaser( this, monitor );
}
/// <summary>
/// Disposable value type.
/// Note that the Dispose explicit implementation must not be called more
/// than once. (Using an explicit implementation here and exposing this Releaser
/// type should avoid any misuse.)
/// </summary>
public readonly struct Releaser : IDisposable
{
readonly AsyncLock _lock;
readonly IActivityMonitor _monitor;
internal Releaser( AsyncLock l, IActivityMonitor m )
{
_lock = l;
_monitor = m;
}
void IDisposable.Dispose()
{
_lock.Leave( _monitor );
}
}
/// <summary>
/// Gets whether this lock is currently enter by the <paramref name="monitor"/>.
/// </summary>
/// <param name="monitor">The monitor that identifies the activity.</param>
/// <returns>True if the monitor has entered this lock.</returns>
/// <exception cref="ArgumentNullException">The monitor is null.</exception>
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public bool IsEnteredBy( IActivityMonitor monitor )
{
Throw.CheckNotNullArgument( monitor );
return _current == monitor.Output;
}
/// <summary>
/// Gets whether this lock is currently held.
/// Of course, no sensible decision should be made on this value.
/// </summary>
public bool IsEntered => _current != null;
/// <summary>
/// Asynchronously waits to enter this <see cref="AsyncLock"/>.
/// This MUST NOT be used in a using statement (unfortunately, a Task is IDisposable),
/// use <see cref="LockAsync(IActivityMonitor)"/> for this.
/// </summary>
/// <param name="monitor">The monitor that identifies the activity.</param>
/// <returns>A task that will complete when the lock has been entered.</returns>
/// <exception cref="ArgumentNullException">The monitor is null.</exception>
/// <exception cref="LockRecursionException">Recursion detected and <see cref="LockRecursionPolicy.NoRecursion"/> has been configured.</exception>
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public Task EnterAsync( IActivityMonitor monitor ) => EnterAsync( monitor, Timeout.Infinite, default );
/// <summary>
/// Asynchronously waits to enter this <see cref="AsyncLock"/>.
/// This MUST NOT be used in a using statement (unfortunately, a Task is IDisposable),
/// use <see cref="LockAsync(IActivityMonitor,CancellationToken)"/> for this.
/// </summary>
/// <param name="monitor">The monitor that identifies the activity.</param>
/// <param name="cancel">Cancellation token.</param>
/// <returns>A task that will complete when the lock has been entered.</returns>
/// <exception cref="ArgumentNullException">The monitor is null.</exception>
/// <exception cref="LockRecursionException">Recursion detected and <see cref="LockRecursionPolicy.NoRecursion"/> has been configured.</exception>
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public Task EnterAsync( IActivityMonitor monitor, CancellationToken cancel ) => EnterAsync( monitor, Timeout.Infinite, cancel );
/// <summary>
/// Asynchronously waits to enter this <see cref="AsyncLock"/>, using a 32-bit signed integer to measure the time interval,
/// while observing a <see cref="CancellationToken"/>.
/// This MUST NOT be used in a using statement (unfortunately, a Task is IDisposable),
/// use <see cref="LockAsync(IActivityMonitor)"/> for this.
/// </summary>
/// <param name="monitor">The monitor that identifies the activity.</param>
/// <param name="millisecondsTimeout">
/// The number of milliseconds to wait, or <see cref="Timeout.Infinite"/>(-1) to wait indefinitely.
/// </param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to observe.</param>
/// <returns>
/// A task that will complete with a result of true if the current thread successfully entered
/// the <see cref="AsyncLock"/>, otherwise with a result of false.
/// </returns>
/// <exception cref="ArgumentNullException">The monitor is null.</exception>
/// <exception cref="System.ObjectDisposedException">The current instance has already been
/// disposed.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a negative number other than -1,
/// which represents an infinite time-out.
/// </exception>
/// <exception cref="LockRecursionException">Recursion detected and <see cref="LockRecursionPolicy.NoRecursion"/> has been configured.</exception>
public async Task<bool> EnterAsync( IActivityMonitor monitor, int millisecondsTimeout, CancellationToken cancellationToken )
{
Throw.CheckNotNullArgument( monitor );
if( _current == monitor.Output )
{
if( _policy == LockRecursionPolicy.NoRecursion ) ThrowLockRecursion( Name );
++_recCount;
Gate.O( monitor )?.UnfilteredLog( LogLevel.Warn | LogLevel.IsFiltered,
ActivityMonitor.Tags.Empty,
$"Asynchronously reentered AsyncLock '{_name}', recursion count: {_recCount}.",
null );
return true;
}
if( await _semaphore.WaitAsync( millisecondsTimeout, cancellationToken ).ConfigureAwait( false ) )
{
Throw.DebugAssert( _recCount == 0 );
Gate.O( monitor )?.UnfilteredLog( LogLevel.Trace | LogLevel.IsFiltered,
ActivityMonitor.Tags.Empty,
$"Asynchronously entered AsyncLock '{_name}'.",
null );
_current = monitor.Output;
return true;
}
return false;
}
/// <summary>
/// Blocks the current thread until it can enter the <see cref="AsyncLock"/>.
/// </summary>
/// <param name="monitor">The monitor that identifies the activity.</param>
/// <exception cref="ArgumentNullException">The monitor is null.</exception>
/// <exception cref="System.ObjectDisposedException">The current instance has already been
/// disposed.</exception>
/// <exception cref="LockRecursionException">Recursion detected and <see cref="LockRecursionPolicy.NoRecursion"/> has been configured.</exception>
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void Enter( IActivityMonitor monitor ) => Enter( monitor, Timeout.Infinite, CancellationToken.None );
/// <summary>
/// Blocks the current thread until it can enter the <see cref="AsyncLock"/>.
/// </summary>
/// <param name="monitor">The monitor that identifies the activity.</param>
/// <param name="cancel">Cancellation token.</param>
/// <exception cref="ArgumentNullException">The monitor is null.</exception>
/// <exception cref="System.ObjectDisposedException">The current instance has already been
/// disposed.</exception>
/// <exception cref="LockRecursionException">Recursion detected and <see cref="LockRecursionPolicy.NoRecursion"/> has been configured.</exception>
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void Enter( IActivityMonitor monitor, CancellationToken cancel ) => Enter( monitor, Timeout.Infinite, cancel );
/// <summary>
/// Blocks the current thread until it can enter this <see cref="AsyncLock"/>, using a 32-bit signed integer to measure the
/// time interval in milliseconds, while observing a <see cref="System.Threading.CancellationToken"/>.
/// </summary>
/// <param name="monitor">The monitor that identifies the activity.</param>
/// <param name="millisecondsTimeout">
/// The number of milliseconds to wait, or <see cref="Timeout.Infinite"/>(-1) to
/// wait indefinitely.
/// </param>
/// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> to observe.</param>
/// <returns>true if the current thread successfully entered the <see cref="AsyncLock"/>; otherwise, false.</returns>
/// <exception cref="ArgumentNullException">The monitor is null.</exception>
/// <exception cref="System.ObjectDisposedException">The current instance has already been
/// disposed.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a negative number other than -1,
/// which represents an infinite time-out.
/// </exception>
/// <exception cref="LockRecursionException">Recursion detected and <see cref="LockRecursionPolicy.NoRecursion"/> has been configured.</exception>
public bool Enter( IActivityMonitor monitor, int millisecondsTimeout, CancellationToken cancellationToken )
{
Throw.CheckNotNullArgument( monitor );
if( _current == monitor.Output )
{
if( _policy == LockRecursionPolicy.NoRecursion ) ThrowLockRecursion( Name );
++_recCount;
Gate.O( monitor )?.UnfilteredLog( LogLevel.Warn | LogLevel.IsFiltered,
ActivityMonitor.Tags.Empty,
$"Synchronously reentered AsyncLock '{_name}', recursion count: {_recCount}.",
null );
return true;
}
if( _semaphore.Wait( millisecondsTimeout, cancellationToken ) )
{
Throw.DebugAssert( _recCount == 0 );
Gate.O( monitor )?.UnfilteredLog( LogLevel.Trace | LogLevel.IsFiltered,
ActivityMonitor.Tags.Empty,
$"Synchronously entered AsyncLock '{_name}'.",
null );
_current = monitor.Output;
return true;
}
return false;
}
/// <summary>
/// Takes the lock immediately and returns true or returns false.
/// </summary>
/// <param name="m">The monitor that identifies the activity.</param>
/// <returns>true if the lock was taken, false otherwise.</returns>
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public bool TryEnter( IActivityMonitor m ) => Enter( m, 0, default );
/// <summary>
/// Leaves the lock that must have been previously entered by the <paramref name="monitor"/>.
/// </summary>
/// <param name="monitor">The monitor that currently holds this lock.</param>
public void Leave( IActivityMonitor monitor )
{
Throw.CheckNotNullArgument( monitor );
if( _current != monitor.Output )
{
var msg = $"Attempt to Release AsyncLock '{_name}' that has {(_current == null ? "never been acquired" : $"been aquired by another monitor")}.";
ThrowSynchronizationLockException( msg );
return;
}
Throw.DebugAssert( _recCount >= 0 );
if( _recCount == 0 )
{
Gate.O( monitor )?.UnfilteredLog( LogLevel.Trace | LogLevel.IsFiltered,
ActivityMonitor.Tags.Empty,
$"Released AsyncLock '{_name}'.",
null );
_current = null;
_semaphore.Release();
}
else
{
Gate.O( monitor )?.UnfilteredLog( LogLevel.Trace | LogLevel.IsFiltered,
ActivityMonitor.Tags.Empty,
$"Decremented AsyncLock '{_name}', recursion count: {_recCount}.",
null );
--_recCount;
}
}
/// <summary>
/// Overridden to return the name of this lock.
/// </summary>
/// <returns>The name of this lock.</returns>
public override string ToString() => _name;
static void ThrowLockRecursion( string name )
{
throw new LockRecursionException( name );
}
static void ThrowSynchronizationLockException( string msg )
{
throw new SynchronizationLockException( msg );
}
}