A lightweight mutual exclusion object which supports waiting with cancellation and prevents recursion (i.e. you may not call Wait if you already hold the lock)

The NonReentrantLock provides a lightweight mutual exclusion class that doesn't use Windows kernel synchronization primitives.

The implementation is distilled from the workings of T:System.Threading.SemaphoreSlim The basic idea is that we use a regular sync object (Monitor.Enter/Exit) to guard the setting of an 'owning thread' field. If, during the Wait, we find the lock is held by someone else then we register a cancellation callback and enter a "Monitor.Wait" loop. If the cancellation callback fires, then it "pulses" all the waiters to wake them up and check for cancellation. Waiters are also "pulsed" when leaving the lock.

All public members of NonReentrantLock are thread-safe and may be used concurrently from multiple threads.

Beispiel #1
0
 public CancellableLazy(Func <CancellationToken, T> valueFactory)
 {
     _gate         = new NonReentrantLock();
     _valueFactory = valueFactory;
 }
Beispiel #2
0
 public SemaphoreDisposer(NonReentrantLock semaphore)
 {
     this.semaphore = semaphore;
 }
Beispiel #3
0
 public static SemaphoreDisposer DisposableWait(this NonReentrantLock semaphore, CancellationToken cancellationToken = default(CancellationToken))
 {
     semaphore.Wait(cancellationToken);
     return(new SemaphoreDisposer(semaphore));
 }
 public SemaphoreDisposer(NonReentrantLock semaphore)
 {
     this.semaphore = semaphore;
 }