-
Notifications
You must be signed in to change notification settings - Fork 148
/
AsyncReaderWriterLock.cs
2879 lines (2579 loc) · 118 KB
/
AsyncReaderWriterLock.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
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.VisualStudio.Threading;
/// <summary>
/// A non-blocking lock that allows concurrent access, exclusive access, or concurrent with upgradeability to exclusive access.
/// </summary>
/// <remarks>
/// We have to use a custom awaitable rather than simply returning Task{LockReleaser} because
/// we have to set CallContext data in the context of the person receiving the lock,
/// which requires that we get to execute code at the start of the continuation (whether we yield or not).
/// </remarks>
/// <devnotes>
/// Considering this class to be a state machine, the states are:
/// <code>
/// <![CDATA[
/// -------------
/// | | <-----> READERS
/// | IDLE | <-----> UPGRADEABLE READER + READERS -----> UPGRADED WRITER --\
/// | NO LOCKS | ^ |
/// | | |--- RE-ENTER CONCURRENCY PREP <--/
/// | | <-----> WRITER
/// -------------
/// ]]>
/// </code>
/// </devnotes>
public partial class AsyncReaderWriterLock : IDisposable
{
/// <summary>
/// A time delay to check whether pending writer lock and reader locks forms a deadlock.
/// </summary>
private static readonly TimeSpan DefaultDeadlockCheckTimeout = TimeSpan.FromSeconds(3);
/// <summary>
/// The default SynchronizationContext to schedule work after issuing a lock.
/// </summary>
private static readonly SynchronizationContext DefaultSynchronizationContext = new SynchronizationContext();
/// <summary>
/// The object to acquire a Monitor-style lock on for all field access on this instance.
/// </summary>
private readonly object syncObject = new object();
/// <summary>
/// A JoinableTaskContext used to resolve dependencies between read locks to lead into deadlocks when there is a pending write lock.
/// </summary>
private readonly JoinableTaskContext? joinableTaskContext;
/// <summary>
/// A CallContext-local reference to the Awaiter that is on the top of the stack (most recently acquired).
/// </summary>
private readonly AsyncLocal<Awaiter> topAwaiter = new AsyncLocal<Awaiter>();
/// <summary>
/// The set of read locks that are issued and active.
/// </summary>
/// <remarks>
/// Many readers are allowed concurrently. Also, readers may re-enter read locks (recursively)
/// each of which gets an element in this set.
/// </remarks>
private readonly HashSet<Awaiter> issuedReadLocks = new HashSet<Awaiter>();
/// <summary>
/// The set of upgradeable read locks that are issued and active.
/// </summary>
/// <remarks>
/// Although only one upgradeable read lock can be held at a time, this set may have more
/// than one element because that one lock holder may enter the lock it already possesses
/// multiple times.
/// </remarks>
private readonly HashSet<Awaiter> issuedUpgradeableReadLocks = new HashSet<Awaiter>();
/// <summary>
/// The set of write locks that are issued and active.
/// </summary>
/// <remarks>
/// Although only one write lock can be held at a time, this set may have more
/// than one element because that one lock holder may enter the lock it already possesses
/// multiple times.
/// Although this lock is mutually exclusive, there *may* be elements in the
/// <see cref="issuedUpgradeableReadLocks"/> set if the write lock was upgraded from a reader.
/// Also note that some elements in this may themselves be upgradeable readers if they have
/// the <see cref="LockFlags.StickyWrite"/> flag.
/// </remarks>
private readonly HashSet<Awaiter> issuedWriteLocks = new HashSet<Awaiter>();
/// <summary>
/// A queue of readers waiting to obtain the concurrent read lock.
/// </summary>
private readonly Queue<Awaiter> waitingReaders = new Queue<Awaiter>();
/// <summary>
/// A queue of upgradeable readers waiting to obtain a lock.
/// </summary>
private readonly Queue<Awaiter> waitingUpgradeableReaders = new Queue<Awaiter>();
/// <summary>
/// A queue of writers waiting to obtain an exclusive lock.
/// </summary>
private readonly Queue<Awaiter> waitingWriters = new Queue<Awaiter>();
/// <summary>
/// The source of the <see cref="Completion"/> task, which transitions to completed after
/// the <see cref="Complete"/> method is called and all issued locks have been released.
/// </summary>
private readonly TaskCompletionSource<object?> completionSource = new TaskCompletionSource<object?>();
/// <summary>
/// The queue of callbacks to invoke when the currently held write lock is totally released.
/// </summary>
/// <remarks>
/// If the write lock is released to an upgradeable read lock, these callbacks are fired synchronously
/// with respect to the writer who is releasing the lock. Otherwise, the callbacks are invoked
/// asynchronously with respect to the releasing thread.
/// </remarks>
private readonly Queue<Func<Task>> beforeWriteReleasedCallbacks = new Queue<Func<Task>>();
/// <summary>
/// A value indicating whether extra resources should be spent to collect diagnostic information
/// that may be useful in deadlock investigations.
/// </summary>
private bool captureDiagnostics;
/// <summary>
/// A flag indicating whether we're currently running code to prepare for re-entering concurrency mode
/// after releasing an exclusive lock. The Awaiter being released is the non-null value.
/// </summary>
private volatile Awaiter? reenterConcurrencyPrepRunning;
/// <summary>
/// A flag indicating that the <see cref="Complete"/> method has been called, indicating that no
/// new top-level lock requests should be serviced.
/// </summary>
private bool completeInvoked;
/// <summary>
/// A helper class to produce ETW trace events.
/// </summary>
private EventsHelper etw;
/// <summary>
/// A timer to recheck potential deadlock caused by pending writer locks.
/// </summary>
private Timer? pendingWriterLockDeadlockCheckTimer;
/// <summary>
/// Initializes a new instance of the <see cref="AsyncReaderWriterLock"/> class.
/// </summary>
public AsyncReaderWriterLock()
: this(joinableTaskContext: null, captureDiagnostics: false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AsyncReaderWriterLock"/> class.
/// </summary>
/// <param name="captureDiagnostics">
/// <see langword="true" /> to spend additional resources capturing diagnostic details that can be used
/// to analyze deadlocks or other issues.</param>
public AsyncReaderWriterLock(bool captureDiagnostics)
: this(joinableTaskContext: null, captureDiagnostics)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AsyncReaderWriterLock"/> class.
/// </summary>
/// <param name="joinableTaskContext">
/// A JoinableTaskContext to help resolve deadlocks caused by interdependency between top read lock tasks when there is a pending write lock blocking one of them.
/// </param>
/// <param name="captureDiagnostics">
/// <see langword="true" /> to spend additional resources capturing diagnostic details that can be used
/// to analyze deadlocks or other issues.</param>
public AsyncReaderWriterLock(JoinableTaskContext? joinableTaskContext, bool captureDiagnostics = false)
{
this.etw = new EventsHelper(this);
this.joinableTaskContext = joinableTaskContext;
this.captureDiagnostics = captureDiagnostics;
}
/// <summary>
/// Flags that modify default lock behavior.
/// </summary>
[Flags]
public enum LockFlags
{
/// <summary>
/// The default behavior applies.
/// </summary>
None = 0x0,
/// <summary>
/// Causes an upgradeable reader to remain in an upgraded-write state once upgraded,
/// even after the nested write lock has been released.
/// </summary>
/// <remarks>
/// This is useful when you have a batch of possible write operations to apply, which
/// may or may not actually apply in the end, but if any of them change anything,
/// all of their changes should be seen atomically (within a single write lock).
/// This approach is preferable to simply acquiring a write lock around the batch of
/// potential changes because it doesn't defeat concurrent readers until it knows there
/// is a change to actually make.
/// </remarks>
StickyWrite = 0x1,
}
/// <summary>
/// An enumeration of the kinds of locks supported by this class.
/// </summary>
internal enum LockKind
{
/// <summary>
/// A lock that supports concurrently executing threads that hold this same lock type.
/// Holders of this lock may not obtain a <see cref="LockKind.Write"/> lock without first
/// releasing all their <see cref="LockKind.Read"/> locks.
/// </summary>
Read,
/// <summary>
/// A lock that may run concurrently with standard readers, but is exclusive of any other
/// upgradeable readers. Holders of this lock are allowed to obtain a write lock while
/// holding this lock to guarantee continuity of state between what they read and what they write.
/// </summary>
UpgradeableRead,
/// <summary>
/// A mutually exclusive lock.
/// </summary>
Write,
}
/// <summary>
/// Gets a value indicating whether any kind of lock is held by the caller and can
/// be immediately used given the caller's context.
/// </summary>
public bool IsAnyLockHeld
{
get { return this.IsReadLockHeld || this.IsUpgradeableReadLockHeld || this.IsWriteLockHeld; }
}
/// <summary>
/// Gets a value indicating whether any kind of lock is held by the caller without regard
/// to the lock compatibility of the caller's context.
/// </summary>
public bool IsAnyPassiveLockHeld
{
get { return this.IsPassiveReadLockHeld || this.IsPassiveUpgradeableReadLockHeld || this.IsPassiveWriteLockHeld; }
}
/// <summary>
/// Gets a value indicating whether the caller holds a read lock.
/// </summary>
/// <remarks>
/// This property returns <see langword="false" /> if any other lock type is held, unless
/// within that alternate lock type this lock is also nested.
/// </remarks>
public bool IsReadLockHeld
{
get { return this.IsLockHeld(LockKind.Read); }
}
/// <summary>
/// Gets a value indicating whether a read lock is held by the caller without regard
/// to the lock compatibility of the caller's context.
/// </summary>
/// <remarks>
/// This property returns <see langword="false" /> if any other lock type is held, unless
/// within that alternate lock type this lock is also nested.
/// </remarks>
public bool IsPassiveReadLockHeld
{
get { return this.IsLockHeld(LockKind.Read, checkSyncContextCompatibility: false, allowNonLockSupportingContext: true); }
}
/// <summary>
/// Gets a value indicating whether the caller holds an upgradeable read lock.
/// </summary>
/// <remarks>
/// This property returns <see langword="false" /> if any other lock type is held, unless
/// within that alternate lock type this lock is also nested.
/// </remarks>
public bool IsUpgradeableReadLockHeld
{
get { return this.IsLockHeld(LockKind.UpgradeableRead); }
}
/// <summary>
/// Gets a value indicating whether an upgradeable read lock is held by the caller without regard
/// to the lock compatibility of the caller's context.
/// </summary>
/// <remarks>
/// This property returns <see langword="false" /> if any other lock type is held, unless
/// within that alternate lock type this lock is also nested.
/// </remarks>
public bool IsPassiveUpgradeableReadLockHeld
{
get { return this.IsLockHeld(LockKind.UpgradeableRead, checkSyncContextCompatibility: false, allowNonLockSupportingContext: true); }
}
/// <summary>
/// Gets a value indicating whether the caller holds a write lock.
/// </summary>
/// <remarks>
/// This property returns <see langword="false" /> if any other lock type is held, unless
/// within that alternate lock type this lock is also nested.
/// </remarks>
public bool IsWriteLockHeld
{
get { return this.IsLockHeld(LockKind.Write); }
}
/// <summary>
/// Gets a value indicating whether a write lock is held by the caller without regard
/// to the lock compatibility of the caller's context.
/// </summary>
/// <remarks>
/// This property returns <see langword="false" /> if any other lock type is held, unless
/// within that alternate lock type this lock is also nested.
/// </remarks>
public bool IsPassiveWriteLockHeld
{
get { return this.IsLockHeld(LockKind.Write, checkSyncContextCompatibility: false, allowNonLockSupportingContext: true); }
}
/// <summary>
/// Gets a task whose completion signals that this lock will no longer issue locks.
/// </summary>
/// <remarks>
/// This task only transitions to a complete state after a call to <see cref="Complete"/>.
/// </remarks>
public Task Completion
{
get { return this.completionSource.Task; }
}
/// <summary>
/// Gets the object used to synchronize access to this instance's fields.
/// </summary>
protected object SyncObject
{
get { return this.syncObject; }
}
/// <summary>
/// Gets the lock held by the caller's execution context.
/// </summary>
protected LockHandle AmbientLock
{
get { return new LockHandle(this.GetFirstActiveSelfOrAncestor(this.topAwaiter.Value)); }
}
/// <summary>
/// Gets or sets a value indicating whether additional resources should be spent to collect
/// information that would be useful in diagnosing deadlocks, etc.
/// </summary>
protected bool CaptureDiagnostics
{
get { return this.captureDiagnostics; }
set { this.captureDiagnostics = value; }
}
/// <summary>
/// Gets a time delay to check whether pending writer lock and reader locks forms a deadlock.
/// </summary>
protected virtual TimeSpan DeadlockCheckTimeout => DefaultDeadlockCheckTimeout;
/// <summary>
/// Gets a value indicating whether the current thread is allowed to
/// hold an active lock.
/// </summary>
/// <remarks>
/// The default implementation of this property returns <see langword="true" />
/// when the calling thread is NOT an STA thread.
/// This property may be overridden to return <see langword="false" />
/// on threads that may compromise the integrity of the lock.
/// </remarks>
protected virtual bool CanCurrentThreadHoldActiveLock
{
get { return Thread.CurrentThread.GetApartmentState() != ApartmentState.STA; }
}
/// <summary>
/// Gets a value indicating whether the current SynchronizationContext is one that is not supported
/// by this lock.
/// </summary>
protected virtual bool IsUnsupportedSynchronizationContext
{
get
{
SynchronizationContext? ctxt = SynchronizationContext.Current;
bool supported = ctxt is null || ctxt is NonConcurrentSynchronizationContext;
return !supported;
}
}
/// <summary>
/// Obtains a read lock, asynchronously awaiting for the lock if it is not immediately available.
/// </summary>
/// <param name="cancellationToken">
/// A token whose cancellation indicates lost interest in obtaining the lock.
/// A canceled token does not release a lock that has already been issued. But if the lock isn't immediately available,
/// a canceled token will cause the code that is waiting for the lock to resume with an <see cref="OperationCanceledException"/>.
/// </param>
/// <returns>An awaitable object whose result is the lock releaser.</returns>
public Awaitable ReadLockAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return new Awaitable(this, LockKind.Read, LockFlags.None, cancellationToken);
}
/// <summary>
/// Obtains an upgradeable read lock, asynchronously awaiting for the lock if it is not immediately available.
/// </summary>
/// <param name="cancellationToken">
/// A token whose cancellation indicates lost interest in obtaining the lock.
/// A canceled token does not release a lock that has already been issued. But if the lock isn't immediately available,
/// a canceled token will cause the code that is waiting for the lock to resume with an <see cref="OperationCanceledException"/>.
/// </param>
/// <returns>An awaitable object whose result is the lock releaser.</returns>
public Awaitable UpgradeableReadLockAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return new Awaitable(this, LockKind.UpgradeableRead, LockFlags.None, cancellationToken);
}
/// <summary>
/// Obtains a read lock, asynchronously awaiting for the lock if it is not immediately available.
/// </summary>
/// <param name="options">Modifications to normal lock behavior.</param>
/// <param name="cancellationToken">
/// A token whose cancellation indicates lost interest in obtaining the lock.
/// A canceled token does not release a lock that has already been issued. But if the lock isn't immediately available,
/// a canceled token will cause the code that is waiting for the lock to resume with an <see cref="OperationCanceledException"/>.
/// </param>
/// <returns>An awaitable object whose result is the lock releaser.</returns>
public Awaitable UpgradeableReadLockAsync(LockFlags options, CancellationToken cancellationToken = default(CancellationToken))
{
return new Awaitable(this, LockKind.UpgradeableRead, options, cancellationToken);
}
/// <summary>
/// Obtains a write lock, asynchronously awaiting for the lock if it is not immediately available.
/// </summary>
/// <param name="cancellationToken">
/// A token whose cancellation indicates lost interest in obtaining the lock.
/// A canceled token does not release a lock that has already been issued. But if the lock isn't immediately available,
/// a canceled token will cause the code that is waiting for the lock to resume with an <see cref="OperationCanceledException"/>.
/// </param>
/// <returns>An awaitable object whose result is the lock releaser.</returns>
public Awaitable WriteLockAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return new Awaitable(this, LockKind.Write, LockFlags.None, cancellationToken);
}
/// <summary>
/// Obtains a write lock, asynchronously awaiting for the lock if it is not immediately available.
/// </summary>
/// <param name="options">Modifications to normal lock behavior.</param>
/// <param name="cancellationToken">
/// A token whose cancellation indicates lost interest in obtaining the lock.
/// A canceled token does not release a lock that has already been issued. But if the lock isn't immediately available,
/// a canceled token will cause the code that is waiting for the lock to resume with an <see cref="OperationCanceledException"/>.
/// </param>
/// <returns>An awaitable object whose result is the lock releaser.</returns>
public Awaitable WriteLockAsync(LockFlags options, CancellationToken cancellationToken = default(CancellationToken))
{
return new Awaitable(this, LockKind.Write, options, cancellationToken);
}
/// <summary>
/// Prevents use or visibility of the caller's lock(s) until the returned value is disposed.
/// </summary>
/// <returns>The value to dispose to restore lock visibility.</returns>
/// <remarks>
/// This can be used by a write lock holder that is about to fork execution to avoid
/// two threads simultaneously believing they hold the exclusive write lock.
/// The lock should be hidden just before kicking off the work and can be restored immediately
/// after kicking off the work.
/// </remarks>
public Suppression HideLocks()
{
return new Suppression(this);
}
/// <summary>
/// Causes new top-level lock requests to be rejected and the <see cref="Completion"/> task to transition
/// to a completed state after any issued locks have been released.
/// </summary>
public void Complete()
{
lock (this.syncObject)
{
this.completeInvoked = true;
this.CompleteIfAppropriate();
}
}
/// <summary>
/// Registers a callback to be invoked when the write lock held by the caller is
/// about to be ultimately released (outermost write lock).
/// </summary>
/// <param name="action">
/// The asynchronous delegate to invoke.
/// Access to the write lock is provided throughout the asynchronous invocation.
/// </param>
/// <remarks>
/// This supports some scenarios VC++ has where change event handlers need to inspect changes,
/// or follow up with other changes to respond to earlier changes, at the conclusion of the lock.
/// This method is safe to call from within a previously registered callback, in which case the
/// registered callback will run when previously registered callbacks have completed execution.
/// If the write lock is released to an upgradeable read lock, these callbacks are fired synchronously
/// with respect to the writer who is releasing the lock. Otherwise, the callbacks are invoked
/// asynchronously with respect to the releasing thread.
/// </remarks>
public void OnBeforeWriteLockReleased(Func<Task> action)
{
Requires.NotNull(action, nameof(action));
lock (this.syncObject)
{
if (!this.IsWriteLockHeld)
{
throw new InvalidOperationException();
}
this.beforeWriteReleasedCallbacks.Enqueue(action);
}
}
/// <inheritdoc/>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes managed and unmanaged resources held by this instance.
/// </summary>
/// <param name="disposing"><see langword="true" /> if <see cref="Dispose()"/> was called; <see langword="false" /> if the object is being finalized.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
Timer? timerToDispose = null;
lock (this.syncObject)
{
timerToDispose = this.pendingWriterLockDeadlockCheckTimer;
this.pendingWriterLockDeadlockCheckTimer = null;
}
timerToDispose?.Dispose();
}
}
/// <summary>
/// Checks whether the aggregated flags from all locks in the lock stack satisfy the specified flag(s).
/// </summary>
/// <param name="flags">The flag(s) that must be specified for a <see langword="true" /> result.</param>
/// <param name="handle">The head of the lock stack to consider.</param>
/// <returns><see langword="true" /> if all the specified flags are found somewhere in the lock stack; <see langword="false" /> otherwise.</returns>
protected bool LockStackContains(LockFlags flags, LockHandle handle)
{
LockFlags aggregateFlags = LockFlags.None;
Awaiter? awaiter = handle.Awaiter;
if (awaiter is object)
{
lock (this.syncObject)
{
while (awaiter is object)
{
if (this.IsLockActive(awaiter, considerStaActive: true, checkSyncContextCompatibility: true))
{
aggregateFlags |= awaiter.Options;
if ((aggregateFlags & flags) == flags)
{
return true;
}
}
awaiter = awaiter.NestingLock;
}
}
}
return (aggregateFlags & flags) == flags;
}
/// <summary>
/// Returns the aggregate of the lock flags for all nested locks.
/// </summary>
/// <remarks>
/// This is not redundant with <see cref="LockStackContains(LockFlags, LockHandle)"/> because that returns fast
/// once the presence of certain flag(s) is determined, whereas this will aggregate all flags,
/// some of which may be defined by derived types.
/// </remarks>
protected LockFlags GetAggregateLockFlags()
{
LockFlags aggregateFlags = LockFlags.None;
Awaiter? awaiter = this.topAwaiter.Value;
if (awaiter is object)
{
lock (this.syncObject)
{
while (awaiter is object)
{
if (this.IsLockActive(awaiter, considerStaActive: true, checkSyncContextCompatibility: true))
{
aggregateFlags |= awaiter.Options;
}
awaiter = awaiter.NestingLock;
}
}
}
return aggregateFlags;
}
/// <summary>
/// Fired when any lock is being released.
/// </summary>
/// <param name="exclusiveLockRelease"><see langword="true" /> if the last write lock that the caller holds is being released; <see langword="false" /> otherwise.</param>
/// <param name="releasingLock">The lock being released.</param>
/// <returns>A task whose completion signals the conclusion of the asynchronous operation.</returns>
protected virtual Task OnBeforeLockReleasedAsync(bool exclusiveLockRelease, LockHandle releasingLock)
{
// Raise the write release lock event if and only if this is the last write that is about to be released.
// Also check that issued read lock count is 0, because these callbacks themselves may acquire read locks
// on top of this write lock that hasn't quite gone away yet, and when they release their read lock,
// that shouldn't trigger a recursive call of the event.
if (exclusiveLockRelease)
{
return this.OnBeforeExclusiveLockReleasedAsync();
}
else
{
return Task.CompletedTask;
}
}
/// <summary>
/// Fired when the last write lock is about to be released.
/// </summary>
/// <returns>A task whose completion signals the conclusion of the asynchronous operation.</returns>
protected virtual Task OnBeforeExclusiveLockReleasedAsync()
{
lock (this.SyncObject)
{
// While this method is called when the last write lock is about to be released,
// a derived type may override this method and have already taken an additional write lock,
// so only state our assumption in the non-derivation case.
Assumes.True(this.issuedWriteLocks.Count == 1 || !this.GetType().Equals(typeof(AsyncReaderWriterLock)));
if (this.beforeWriteReleasedCallbacks.Count > 0)
{
return this.InvokeBeforeWriteLockReleaseHandlersAsync();
}
else
{
return Task.CompletedTask;
}
}
}
/// <summary>
/// Get the task scheduler to execute the continuation when the lock is acquired.
/// AsyncReaderWriterLock uses a special <see cref="SynchronizationContext"/> to handle execusive locks, and will ignore task scheduler provided, so this is only used in a read lock scenario.
/// This method is called within the execution context to wait the read lock, so it can pick up <see cref="TaskScheduler"/> based on the current execution context.
/// Note: the task scheduler is only used, when the lock is issued later. If the lock is issued immediately when <see cref="CanCurrentThreadHoldActiveLock"/> returns true, it will be ignored.
/// </summary>
/// <returns>A task scheduler to schedule the continutation task when a lock is issued.</returns>
protected virtual TaskScheduler GetTaskSchedulerForReadLockRequest()
{
return TaskScheduler.Default;
}
/// <summary>
/// Invoked after an exclusive lock is released but before anyone has a chance to enter the lock.
/// </summary>
/// <remarks>
/// This method is called while holding a private lock in order to block future lock consumers till this method is finished.
/// </remarks>
protected virtual Task OnExclusiveLockReleasedAsync()
{
return Task.CompletedTask;
}
/// <summary>
/// Invoked when a top-level upgradeable read lock is released, leaving no remaining (write) lock.
/// </summary>
protected virtual void OnUpgradeableReadLockReleased()
{
}
/// <summary>
/// Invoked when the lock detects an internal error or illegal usage pattern that
/// indicates a serious flaw that should be immediately reported to the application
/// and/or bring down the process to avoid hangs or data corruption.
/// </summary>
/// <param name="ex">The exception that captures the details of the failure.</param>
/// <returns>An exception that may be returned by some implementations of tis method for he caller to rethrow.</returns>
protected virtual Exception OnCriticalFailure(Exception ex)
{
Requires.NotNull(ex, nameof(ex));
Report.Fail(ex.Message);
Environment.FailFast(ex.ToString(), ex);
throw Assumes.NotReachable();
}
/// <summary>
/// Invoked when the lock detects an internal error or illegal usage pattern that
/// indicates a serious flaw that should be immediately reported to the application
/// and/or bring down the process to avoid hangs or data corruption.
/// </summary>
/// <param name="message">The message to use for the exception.</param>
/// <returns>An exception that may be returned by some implementations of tis method for he caller to rethrow.</returns>
protected Exception OnCriticalFailure(string message)
{
try
{
throw Assumes.Fail(message);
}
catch (Exception ex)
{
throw this.OnCriticalFailure(ex);
}
}
/// <summary>
/// Checks whether the specified lock has any active nested locks.
/// </summary>
private static bool HasAnyNestedLocks(Awaiter lck, HashSet<Awaiter> lockCollection)
{
Requires.NotNull(lck, nameof(lck));
Requires.NotNull(lockCollection, nameof(lockCollection));
if (lockCollection.Count > 0)
{
foreach (Awaiter? nestedCandidate in lockCollection)
{
if (nestedCandidate == lck)
{
// This isn't nested -- it's the lock itself.
continue;
}
for (Awaiter? a = nestedCandidate.NestingLock; a is object; a = a.NestingLock)
{
if (a == lck)
{
return true;
}
}
}
}
return false;
}
private static void PendingWriterLockDeadlockWatchingCallback(object? state)
{
var readerWriterLock = (AsyncReaderWriterLock?)state;
Assumes.NotNull(readerWriterLock);
readerWriterLock.TryInvokeAllDependentReadersIfAppropriate();
lock (readerWriterLock.syncObject)
{
readerWriterLock.pendingWriterLockDeadlockCheckTimer?.Change((int)readerWriterLock.DeadlockCheckTimeout.TotalMilliseconds, -1);
}
}
/// <summary>
/// Throws an exception if called on an STA thread.
/// </summary>
private void ThrowIfUnsupportedThreadOrSyncContext()
{
if (!this.CanCurrentThreadHoldActiveLock)
{
Verify.FailOperation(Strings.STAThreadCallerNotAllowed);
}
if (this.IsUnsupportedSynchronizationContext)
{
Verify.FailOperation(Strings.AppliedSynchronizationContextNotAllowed);
}
}
/// <summary>
/// Gets a value indicating whether the caller's thread apartment model and SynchronizationContext
/// is compatible with a lock.
/// </summary>
private bool IsLockSupportingContext(Awaiter? awaiter = null)
{
if (!this.CanCurrentThreadHoldActiveLock || this.IsUnsupportedSynchronizationContext)
{
return false;
}
awaiter = awaiter ?? this.topAwaiter.Value;
if (this.IsLockHeld(LockKind.Write, awaiter, allowNonLockSupportingContext: true, checkSyncContextCompatibility: false) ||
this.IsLockHeld(LockKind.UpgradeableRead, awaiter, allowNonLockSupportingContext: true, checkSyncContextCompatibility: false))
{
if (!(SynchronizationContext.Current is NonConcurrentSynchronizationContext))
{
// Upgradeable read and write locks *must* have the NonConcurrentSynchronizationContext applied.
return false;
}
}
return true;
}
/// <summary>
/// Transitions the <see cref="Completion"/> task to a completed state
/// if appropriate.
/// </summary>
private void CompleteIfAppropriate()
{
Assumes.True(Monitor.IsEntered(this.syncObject));
if (this.completeInvoked &&
!this.completionSource.Task.IsCompleted &&
this.reenterConcurrencyPrepRunning is null &&
this.issuedReadLocks.Count == 0 && this.issuedUpgradeableReadLocks.Count == 0 && this.issuedWriteLocks.Count == 0 &&
this.waitingReaders.Count == 0 && this.waitingUpgradeableReaders.Count == 0 && this.waitingWriters.Count == 0)
{
// We must use another task to asynchronously transition this so we don't inadvertently execute continuations inline
// while we're holding a lock.
Task.Run(delegate { this.completionSource.TrySetResult(null); });
}
}
/// <summary>
/// Detects which lock types the given lock holder has (including all nested locks).
/// </summary>
/// <param name="awaiter">The most nested lock to be considered.</param>
/// <param name="read">Receives a value indicating whether a read lock is held.</param>
/// <param name="upgradeableRead">Receives a value indicating whether an upgradeable read lock is held.</param>
/// <param name="write">Receives a value indicating whether a write lock is held.</param>
private void AggregateLockStackKinds(Awaiter? awaiter, out bool read, out bool upgradeableRead, out bool write)
{
read = false;
upgradeableRead = false;
write = false;
if (awaiter is object)
{
lock (this.syncObject)
{
while (awaiter is object)
{
// It's possible that this lock has been released (even mid-stack, due to our async nature),
// so only consider locks that are still active.
switch (awaiter.Kind)
{
case LockKind.Read:
read |= this.issuedReadLocks.Contains(awaiter);
break;
case LockKind.UpgradeableRead:
upgradeableRead |= this.issuedUpgradeableReadLocks.Contains(awaiter);
write |= this.IsStickyWriteUpgradedLock(awaiter);
break;
case LockKind.Write:
write |= this.issuedWriteLocks.Contains(awaiter);
break;
}
if (read && upgradeableRead && write)
{
// We've seen it all. Walking the stack further would not provide anything more.
return;
}
awaiter = awaiter.NestingLock;
}
}
}
}
/// <summary>
/// Gets a value indicating whether all issued locks are merely the top-level lock or nesting locks of the specified lock.
/// </summary>
/// <param name="awaiter">The most nested lock.</param>
/// <returns><see langword="true" /> if all issued locks are the specified lock or nesting locks of it.</returns>
private bool AllHeldLocksAreByThisStack(Awaiter? awaiter)
{
Assumes.True(awaiter is null || !this.IsLockHeld(LockKind.Write, awaiter)); // this method doesn't yet handle sticky upgraded read locks (that appear in the write lock set).
lock (this.syncObject)
{
if (awaiter is object)
{
int locksMatched = 0;
while (awaiter is object)
{
if (this.GetActiveLockSet(awaiter.Kind).Contains(awaiter))
{
locksMatched++;
}
awaiter = awaiter.NestingLock;
}
return locksMatched == this.issuedReadLocks.Count + this.issuedUpgradeableReadLocks.Count + this.issuedWriteLocks.Count;
}
else
{
return this.issuedReadLocks.Count == 0 && this.issuedUpgradeableReadLocks.Count == 0 && this.issuedWriteLocks.Count == 0;
}
}
}
/// <summary>
/// Gets a value indicating whether the specified lock is, or is a nested lock of, a given type.
/// </summary>
/// <param name="kind">The kind of lock being queried for.</param>
/// <param name="awaiter">The (possibly nested) lock.</param>
/// <returns><see langword="true" /> if the lock holder (also) holds the specified kind of lock.</returns>
private bool LockStackContains(LockKind kind, Awaiter? awaiter)
{
if (awaiter is object)
{
lock (this.syncObject)
{
HashSet<Awaiter>? lockSet = this.GetActiveLockSet(kind);
while (awaiter is object)
{
// It's possible that this lock has been released (even mid-stack, due to our async nature),
// so only consider locks that are still active.
if (awaiter.Kind == kind && lockSet.Contains(awaiter))
{
return true;
}
if (kind == LockKind.Write && this.IsStickyWriteUpgradedLock(awaiter))
{
return true;
}
awaiter = awaiter.NestingLock;
}
}
}
return false;
}
/// <summary>
/// Checks whether the specified lock is an upgradeable read lock, with a <see cref="LockFlags.StickyWrite"/> flag,
/// which has actually be upgraded.
/// </summary>
/// <param name="awaiter">The lock to test.</param>
/// <returns><see langword="true" /> if the test succeeds; <see langword="false" /> otherwise.</returns>
private bool IsStickyWriteUpgradedLock(Awaiter awaiter)
{
if (awaiter.Kind == LockKind.UpgradeableRead && (awaiter.Options & LockFlags.StickyWrite) == LockFlags.StickyWrite)
{
lock (this.syncObject)
{
return this.issuedWriteLocks.Contains(awaiter);
}
}
return false;
}
/// <summary>
/// Checks whether the caller's held locks (or the specified lock stack) includes an active lock of the specified type.
/// Always <see langword="false" /> when called on an STA thread.
/// </summary>
/// <param name="kind">The type of lock to check for.</param>
/// <param name="awaiter">The most nested lock of the caller, or null to look up the caller's lock in the CallContext.</param>
/// <param name="checkSyncContextCompatibility"><see langword="true" /> to throw an exception if the caller has an exclusive lock but not an associated SynchronizationContext.</param>
/// <param name="allowNonLockSupportingContext"><see langword="true" /> to return true when a lock is held but unusable because of the context of the caller.</param>
/// <returns><see langword="true" /> if the caller holds active locks of the given type; <see langword="false" /> otherwise.</returns>
private bool IsLockHeld(LockKind kind, Awaiter? awaiter = null, bool checkSyncContextCompatibility = true, bool allowNonLockSupportingContext = false)
{
if (allowNonLockSupportingContext || this.IsLockSupportingContext(awaiter))
{
lock (this.syncObject)
{
awaiter = awaiter ?? this.topAwaiter.Value;
if (checkSyncContextCompatibility)
{
this.CheckSynchronizationContextAppropriateForLock(awaiter);
}