GuidesScope a lock
Scope a lock
Take a SemaphoreSlim or ReaderWriterLockSlim lock in a using statement, in a struct that allocates nothing.
A lock you take by hand has to be released on every path out of the code that holds it. A scope takes the lock and releases it when the using statement ends, even when the code throws. This page shows how to scope a semaphore, cancel the wait, scope a reader-writer lock, why a scope is a struct, and what to watch for.
Scope a semaphore
Section titled “Scope a semaphore”Lock() on a SemaphoreSlim waits synchronously and LockAsync() waits asynchronously. Both take a CancellationToken, and both return a scope that releases the semaphore when you dispose it.
using var semaphore = new SemaphoreSlim(1, 1);var countInScope = -1;using (await semaphore.LockAsync()){ countInScope = semaphore.CurrentCount; // 0 while the scope holds it}// semaphore.CurrentCount == 1Cancel the wait
Section titled “Cancel the wait”When the token is cancelled while the wait is pending, the wait throws OperationCanceledException and returns no scope, so there is nothing to release.
using var semaphore = new SemaphoreSlim(0, 1); // another scope holds itusing var cancelled = new CancellationTokenSource();await cancelled.CancelAsync();
var acquired = false;try{ using (await semaphore.LockAsync(cancelled.Token)) { acquired = true; }}catch (OperationCanceledException){ // the wait was cancelled: no scope, so nothing to release}
// acquired == false, semaphore.CurrentCount == 0Scope a reader-writer lock
Section titled “Scope a reader-writer lock”ReadLock(), WriteLock() and UpgradeableReadLock() on a ReaderWriterLockSlim each take that lock and return a scope that exits it.
using var cacheLock = new ReaderWriterLockSlim();var readLockHeld = false;using (cacheLock.ReadLock()){ readLockHeld = cacheLock.IsReadLockHeld; // true while the scope holds it}using (cacheLock.WriteLock()){ // update the cache}// cacheLock.IsWriteLockHeld == falseAn upgradeable read lock lets you read, decide to write, and take the write lock without releasing the read first.
using var cacheLock = new ReaderWriterLockSlim();var writeHeld = false;using (cacheLock.UpgradeableReadLock()){ // read, and decide to write using (cacheLock.WriteLock()) { writeHeld = cacheLock.IsWriteLockHeld; // true }}// cacheLock.IsUpgradeableReadLockHeld == falseWhy a struct
Section titled “Why a struct”The scope is a ValueDisposable<T> built on one cached delegate, so taking a lock allocates nothing, as ADR-1006 records. A struct has no identity, so every copy of a scope releases the lock again, which is why you dispose it once. See once, or on every call.
Pitfalls
Section titled “Pitfalls”Disposing a scope twice releases the lock twice, and a SemaphoreSlim(1, 1) throws when its count would pass the maximum:
using var semaphore = new SemaphoreSlim(1, 1);var scope = semaphore.Lock();scope.Dispose(); // releases the semaphore
var failed = false;try{ scope.Dispose(); // releases it again}catch (SemaphoreFullException){ failed = true; // the count would pass its maximum, 1}- Disposing a scope twice.
- You write
scope.Dispose()twice, or dispose a scope and a copy of it. - What happens: the lock is released twice, as
SemaphoreSlim.Releasewould be. - Write instead: dispose the scope once, through
using.
- You write
- Holding a reader-writer lock across an
await.- You write
using (cacheLock.ReadLock()) { await …; } - What happens: the code after the
awaitcan run on another thread, andReaderWriterLockSlim, which belongs to the thread that entered it, throwsSynchronizationLockExceptionwhen the scope exits. - Write instead:
await semaphore.LockAsync().
- You write