Skip to content

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.

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 == 1

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 it
using 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 == 0

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 == false

An 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 == false

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.

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.Release would be.
    • Write instead: dispose the scope once, through using.
  • Holding a reader-writer lock across an await.
    • You write using (cacheLock.ReadLock()) { await …; }
    • What happens: the code after the await can run on another thread, and ReaderWriterLockSlim, which belongs to the thread that entered it, throws SynchronizationLockException when the scope exits.
    • Write instead: await semaphore.LockAsync().