Before you start
- Check which version of
DotNext.Threading the project references (.csproj or
Directory.Packages.props). This skill describes 6.x. For older versions, verify each
member you use against the XML docs/IntelliSense of the referenced version.
- This skill is applicable in the following scenarios:
- Writing new async code
- Converting existing synchronous code
- If this skill doesn't cover what you need (API details, more examples), find the relevant article
in the documentation index: https://dotnet.github.io/dotNext/llms.txt
All types live in the DotNext.Threading namespace or nested namespaces.
Use Cases
- Use
AsyncExclusiveLock if you need exclusive lock behavior in async code, or you need async-friendly replacement of lock or System.Threading.Monitor. Consider this type as well when System.Threading.Channels.Channel<T> is used to organize the behavior similar to exclusive lock: once the item is placed in the channel, it cannot be removed or canceled without the actual processing by the consumer, but AsyncExclusiveLock supports cancellation of the suspended caller
- Use
AsyncReaderWriterLock if you need reader/writer lock behavior in async code, or you need async-friendly replacement of System.Threading.ReaderWriterLock or System.Threading.ReaderWriterLockSlim classes.
- Use
AsyncAutoResetEvent or AsyncManualResetEvent for signal-based synchronization in async code, or as async-friendly replacement of System.Threading.AutoResetEvent or System.Threading.ManualResetEvent classes.
- Use
AsyncCountdownEvent if you need async-friendly replacement of System.Threading.CountdownEvent class.
- Use
AsyncBarrier if you need async-friendly replacement of System.Threading.Barrier class. Post-phase handling is provided via PostPhase virtual method, which replaces postPhaseAction delegate in the constructor of System.Threading.Barrier class.
- Use
AsyncTrigger to suspend and resume async flows on demand, or as async-friendly replacement of Monitor.Wait/Monitor.Pulse/Monitor.PulseAll: Pulse → Signal(), PulseAll → Signal(resumeAll: true), Wait → WaitAsync(token).
- The trigger is not tied to a lock and has no memory:
Signal() resumes only callers that are already waiting and returns false if there are none. Where a signal must not be lost, use AsyncAutoResetEvent or AsyncManualResetEvent instead.
- For "wait until condition" loops (
while (!condition) Monitor.Wait(obj)), use SpinWaitAsync(condition, token). The condition implements DotNext.ISupplier<bool> (a struct avoids allocation). It is checked before suspending, and a signal resumes the caller only if the condition is true at that moment.
SignalAndWaitAsync(resumeAll, throwOnEmptyQueue, token) resumes waiters and suspends the caller in one step, the async equivalent of the Pulse + Wait handoff.
- Use
await AsyncBridge.WaitAsync(CancellationToken, bool) to replace CancellationToken.WaitHandle.WaitOne() synchronous calls to wait for the cancellation in async methods
- Use
await AsyncBridge.WaitAsync(WaitHandle, TimeSpan, CancellationToken) or await AsyncBridge.WaitAsync(WaitHandle, CancellationToken) to replace WaitHandle.WaitOne() variations of synchronous calls in async methods
- If custom synchronization is needed for async scenarios, consider
QueuedSynchronizer<T> as a base class
Consider rules when using these primitives.
Migration Tips
Read this when existing code uses blocking synchronization and needs to become async.
Typical triggers: CS1996 (await inside lock), thread-pool starvation, or .Wait()/.Result in async code.
- Find every access to the protected state, not just the method that failed to compile. All of them must
switch to the new primitive in the same change. Protecting the same state with the old primitive in some places
and the new one in others leaves it unprotected.
- Replace the primitive and convert each critical section to the
await ...; try { } finally { Release(); } pattern.
- Make the containing methods
async and return ValueTask/Task. Propagate async up the call chain.
Do not work around it with .Result, .Wait() or GetAwaiter().GetResult().
Callers that can't become async yet (public sync API, sync interface implementations, Dispose()): if the
primitive is AsyncExclusiveLock or AsyncReaderWriterLock, keep those callers synchronous on the same lock
instance with TryAcquire(timeout) / TryEnterReadLock(timeout) / TryEnterWriteLock(timeout). Use them instead of
blocking on the async overload. This allows migrating one call chain at a time. See "Mixed sync and async callers"
below for the rules. Note that Monitor.Enter-style unbounded waits become a timeout plus a bool check.
- Add a
CancellationToken parameter and flow it into every acquisition.
- Check the timeout semantics:
Monitor.TryEnter(obj, timeout) → TryAcquireAsync(timeout) (returns bool).
AcquireAsync(timeout) throws TimeoutException instead.
- Check for reentrancy (below) before finishing.
- If the owner type is
IDisposable, dispose the new primitive there, preferably via IAsyncDisposable.
Mixed sync and async callers
AsyncExclusiveLock and AsyncReaderWriterLock can also be acquired synchronously. One lock instance can then
serve callers that have to stay synchronous (sync interface implementations, Dispose(), legacy APIs, code
you are migrating gradually) alongside async callers. Sync and async holders exclude each other and hand the
lock over in both directions.
| Lock |
Blocking, with thread ownership |
Non-blocking attempt, no thread ownership |
AsyncExclusiveLock |
TryAcquire(timeout, token) |
TryAcquire() |
AsyncReaderWriterLock |
TryEnterReadLock(timeout, token), TryEnterWriteLock(timeout, token) |
TryEnterReadLock(), TryEnterWriteLock(), TryUpgradeToWriteLock(), TryEnterWriteLock(in stamp) |
Release is always Release(), the same as for async acquisition.
public void Flush() // must stay synchronous
{
if (!syncRoot.TryAcquire(TimeSpan.FromSeconds(5)))
throw new TimeoutException();
try
{
FlushCore();
}
finally
{
syncRoot.Release();
}
}
- They return
bool and never throw on timeout or cancellation. A canceled token also returns false.
Check the result every time.
- The blocking overloads block the calling thread. Use them only where the caller really can't be async, always with a
finite timeout, and never from async code: there,
await the async overload instead. Blocking thread-pool threads
while async holders need the pool to finish can starve the pool.
- Release on the same thread when the lock was acquired with the blocking overloads. They record the owning thread.
- Recursion detection works only between blocking sync acquisitions on the same thread (
LockRecursionException).
A sync acquisition on a thread that already holds the lock via await, or the other way round, is not detected and
just waits: false after the timeout for sync, forever for async.
TryUpgradeToWriteLock() that returns false has already released the caller's read lock. Don't call Release()
for the read lock afterward. Reacquire if you still need it.
Canonical example
using DotNext.Threading;
public sealed class Inventory : IAsyncDisposable
{
private readonly AsyncExclusiveLock syncRoot = new();
private readonly Dictionary<string, int> stock = new();
public async ValueTask AddAsync(string item, int count, CancellationToken token)
{
await syncRoot.AcquireAsync(token);
try
{
AddCore(item, count); // helper assumes the lock is held; the lock is not reentrant
}
finally
{
syncRoot.Release();
}
}
public async ValueTask<bool> TryRemoveAsync(string item, int count, TimeSpan timeout, CancellationToken token)
{
if (!await syncRoot.TryAcquireAsync(timeout, token))
return false; // timed out; the lock is not held, so don't release it
try
{
if (!stock.TryGetValue(item, out var current) || current < count)
return false;
stock[item] = current - count;
return true;
}
finally
{
syncRoot.Release();
}
}
private void AddCore(string item, int count)
=> stock[item] = stock.GetValueOrDefault(item) + count;
public ValueTask DisposeAsync() => syncRoot.DisposeAsync();
}
Don't use this skill for
- CPU-bound parallelism →
Parallel, PLINQ.
- Producer/consumer queues →
System.Threading.Channels
- Code that is fully synchronous, never awaits while holding the lock, and shares no state with async code.
lock is fine there and faster.
Pitfalls
- Reentrancy.
lock/Monitor and ReaderWriterLockSlim (with LockRecursionPolicy.SupportsRecursion) allow the
owning thread to re-enter. DotNext async locks do not. Async acquisition has no thread owner, so re-entering
simply waits forever. Look for public locked methods calling other public locked methods, and refactor them into
lock-taking entry points plus private helpers that assume the lock is held.
- Thread affinity is gone. After
await, the code may continue on another thread. A lock acquired
asynchronously can be released from any thread. Don't keep thread-local or [ThreadStatic] assumptions inside the critical section.
AsyncLock.AcquireLockAsync(obj) restrictions. It throws InvalidOperationException for ReaderWriterLockSlim,
WaitHandle and ReaderWriterLock instances, and for objects on the runtime's frozen (non-GC) heap such as
string literals. Never lock on strings. For SemaphoreSlim, AsyncExclusiveLock, AsyncReaderWriterLock
and AsyncSharedLock it uses the object itself as the lock. When in doubt, use an explicit AsyncExclusiveLock field.
- Don't keep
lock on sync paths that share state with async ones. If a code path is purely synchronous and hot,
it may be tempting to keep lock there. That is only safe if no async path touches the same state. Otherwise, use
the sync API of the new lock (step 3).
- Upgradeable read locks.
ReaderWriterLockSlim.EnterUpgradeableReadLock keeps the read lock while waiting for the
upgrade. AsyncReaderWriterLock upgrades by releasing the read lock first, so other writers may run in between. A failed
TryUpgradeToWriteLock() / TryUpgradeToWriteLockAsync() leaves the caller holding nothing. Re-validate the state
you read before the upgrade.
- Performance trade-off. Async locks don't block threads while waiting, which improves throughput under contention,
at the cost of higher latency per acquisition than
lock. For short, fully synchronous critical sections that never
share state with async code, lock remains faster.
1---2name: dotnext-threading3description: Async synchronization primitives from the DotNext.Threading NuGet package - async4 exclusive and reader/writer locks (with sync acquisition for mixed callers), auto/manual reset5 events, countdown event, barrier, AsyncTrigger, awaiting WaitHandle/CancellationToken, and6 custom primitives via QueuedSynchronizer<T>. Use when writing async .NET code that needs mutual7 exclusion or signaling without blocking threads, or that must await a WaitHandle or a8 CancellationToken; and when converting lock/Monitor, Monitor.Wait/Pulse, ReaderWriterLockSlim,9 ManualResetEventSlim, AutoResetEvent, CountdownEvent, Barrier or WaitHandle.WaitOne to async,10 e.g. after "CS1996 cannot await in the body of a lock statement".11license: MIT12metadata:13 source: https://skillmd.com/skills/dotnet/dotnext-threading14 dotnext-version: "6.x"15---1617# Before you start18191. Check which version of `DotNext.Threading` the project references (`.csproj` or20 `Directory.Packages.props`). This skill describes 6.x. For older versions, verify each21 member you use against the XML docs/IntelliSense of the referenced version.222. This skill is applicable in the following scenarios:23 - Writing new async code24 - Converting existing synchronous code253. If this skill doesn't cover what you need (API details, more examples), find the relevant article26 in the documentation index: https://dotnet.github.io/dotNext/llms.txt2728All types live in the `DotNext.Threading` namespace or nested namespaces.2930# Use Cases3132- Use `AsyncExclusiveLock` if you need exclusive lock behavior in async code, or you need async-friendly replacement of **lock** or `System.Threading.Monitor`. Consider this type as well when `System.Threading.Channels.Channel<T>` is used to organize the behavior similar to exclusive lock: once the item is placed in the channel, it cannot be removed or canceled without the actual processing by the consumer, but `AsyncExclusiveLock` supports cancellation of the suspended caller33- Use `AsyncReaderWriterLock` if you need reader/writer lock behavior in async code, or you need async-friendly replacement of `System.Threading.ReaderWriterLock` or `System.Threading.ReaderWriterLockSlim` classes.34- Use `AsyncAutoResetEvent` or `AsyncManualResetEvent` for signal-based synchronization in async code, or as async-friendly replacement of `System.Threading.AutoResetEvent` or `System.Threading.ManualResetEvent` classes.35- Use `AsyncCountdownEvent` if you need async-friendly replacement of `System.Threading.CountdownEvent` class.36- Use `AsyncBarrier` if you need async-friendly replacement of `System.Threading.Barrier` class. Post-phase handling is provided via `PostPhase` virtual method, which replaces `postPhaseAction` delegate in the constructor of `System.Threading.Barrier` class.37- Use `AsyncTrigger` to suspend and resume async flows on demand, or as async-friendly replacement of `Monitor.Wait`/`Monitor.Pulse`/`Monitor.PulseAll`: `Pulse` → `Signal()`, `PulseAll` → `Signal(resumeAll: true)`, `Wait` → `WaitAsync(token)`.38 - The trigger is not tied to a lock and has no memory: `Signal()` resumes only callers that are already waiting and returns **false** if there are none. Where a signal must not be lost, use `AsyncAutoResetEvent` or `AsyncManualResetEvent` instead.39 - For "wait until condition" loops (`while (!condition) Monitor.Wait(obj)`), use `SpinWaitAsync(condition, token)`. The condition implements `DotNext.ISupplier<bool>` (a struct avoids allocation). It is checked before suspending, and a signal resumes the caller only if the condition is true at that moment.40 - `SignalAndWaitAsync(resumeAll, throwOnEmptyQueue, token)` resumes waiters and suspends the caller in one step, the async equivalent of the `Pulse` + `Wait` handoff.41- Use `await AsyncBridge.WaitAsync(CancellationToken, bool)` to replace `CancellationToken.WaitHandle.WaitOne()` synchronous calls to wait for the cancellation in async methods42- Use `await AsyncBridge.WaitAsync(WaitHandle, TimeSpan, CancellationToken)` or `await AsyncBridge.WaitAsync(WaitHandle, CancellationToken)` to replace `WaitHandle.WaitOne()` variations of synchronous calls in async methods43- If custom synchronization is needed for async scenarios, consider `QueuedSynchronizer<T>` as a base class4445Consider [rules](references/common_rules.md) when using these primitives.4647# Migration Tips48Read this when existing code uses blocking synchronization and needs to become async.49Typical triggers: `CS1996` (await inside `lock`), thread-pool starvation, or `.Wait()`/`.Result` in async code.50511. Find every access to the protected state, not just the method that failed to compile. All of them must52 switch to the new primitive in the same change. Protecting the same state with the old primitive in some places53 and the new one in others leaves it unprotected.542. Replace the primitive and convert each critical section to the `await ...; try { } finally { Release(); }` pattern.553. Make the containing methods `async` and return `ValueTask`/`Task`. Propagate `async` up the call chain.56 Do not work around it with `.Result`, `.Wait()` or `GetAwaiter().GetResult()`.57 **Callers that can't become async yet** (public sync API, sync interface implementations, `Dispose()`): if the58 primitive is `AsyncExclusiveLock` or `AsyncReaderWriterLock`, keep those callers synchronous on the *same* lock59 instance with `TryAcquire(timeout)` / `TryEnterReadLock(timeout)` / `TryEnterWriteLock(timeout)`. Use them instead of60 blocking on the async overload. This allows migrating one call chain at a time. See "Mixed sync and async callers"61 below for the rules. Note that `Monitor.Enter`-style unbounded waits become a timeout plus a `bool` check.624. Add a `CancellationToken` parameter and flow it into every acquisition.635. Check the timeout semantics: `Monitor.TryEnter(obj, timeout)` → `TryAcquireAsync(timeout)` (returns `bool`).64 `AcquireAsync(timeout)` throws `TimeoutException` instead.656. Check for reentrancy (below) before finishing.667. If the owner type is `IDisposable`, dispose the new primitive there, preferably via `IAsyncDisposable`.6768# Mixed sync and async callers6970`AsyncExclusiveLock` and `AsyncReaderWriterLock` can also be acquired synchronously. One lock instance can then71serve callers that have to stay synchronous (sync interface implementations, `Dispose()`, legacy APIs, code72you are migrating gradually) alongside async callers. Sync and async holders exclude each other and hand the73lock over in both directions.7475| Lock | Blocking, with thread ownership | Non-blocking attempt, no thread ownership |76|---|---|---|77| `AsyncExclusiveLock` | `TryAcquire(timeout, token)` | `TryAcquire()` |78| `AsyncReaderWriterLock` | `TryEnterReadLock(timeout, token)`, `TryEnterWriteLock(timeout, token)` | `TryEnterReadLock()`, `TryEnterWriteLock()`, `TryUpgradeToWriteLock()`, `TryEnterWriteLock(in stamp)` |7980Release is always `Release()`, the same as for async acquisition.8182```csharp83public void Flush() // must stay synchronous84{85 if (!syncRoot.TryAcquire(TimeSpan.FromSeconds(5)))86 throw new TimeoutException();8788 try89 {90 FlushCore();91 }92 finally93 {94 syncRoot.Release();95 }96}97```9899- **They return `bool` and never throw on timeout or cancellation.** A canceled token also returns `false`.100 Check the result every time.101- **The blocking overloads block the calling thread.** Use them only where the caller really can't be async, always with a102 finite timeout, and never from async code: there, `await` the async overload instead. Blocking thread-pool threads103 while async holders need the pool to finish can starve the pool.104- **Release on the same thread** when the lock was acquired with the blocking overloads. They record the owning thread.105- **Recursion detection works only between blocking sync acquisitions on the same thread** (`LockRecursionException`).106 A sync acquisition on a thread that already holds the lock via `await`, or the other way round, is not detected and107 just waits: `false` after the timeout for sync, forever for async.108- **`TryUpgradeToWriteLock()` that returns `false` has already released the caller's read lock.** Don't call `Release()`109 for the read lock afterward. Reacquire if you still need it.110111# Canonical example112113```csharp114using DotNext.Threading;115116public sealed class Inventory : IAsyncDisposable117{118 private readonly AsyncExclusiveLock syncRoot = new();119 private readonly Dictionary<string, int> stock = new();120121 public async ValueTask AddAsync(string item, int count, CancellationToken token)122 {123 await syncRoot.AcquireAsync(token);124 try125 {126 AddCore(item, count); // helper assumes the lock is held; the lock is not reentrant127 }128 finally129 {130 syncRoot.Release();131 }132 }133134 public async ValueTask<bool> TryRemoveAsync(string item, int count, TimeSpan timeout, CancellationToken token)135 {136 if (!await syncRoot.TryAcquireAsync(timeout, token))137 return false; // timed out; the lock is not held, so don't release it138139 try140 {141 if (!stock.TryGetValue(item, out var current) || current < count)142 return false;143144 stock[item] = current - count;145 return true;146 }147 finally148 {149 syncRoot.Release();150 }151 }152153 private void AddCore(string item, int count)154 => stock[item] = stock.GetValueOrDefault(item) + count;155156 public ValueTask DisposeAsync() => syncRoot.DisposeAsync();157}158```159160# Don't use this skill for161162- CPU-bound parallelism → `Parallel`, PLINQ.163- Producer/consumer queues → `System.Threading.Channels`164- Code that is fully synchronous, never awaits while holding the lock, and shares no state with async code.165 `lock` is fine there and faster.166167# Pitfalls168169- **Reentrancy.** `lock`/`Monitor` and `ReaderWriterLockSlim` (with `LockRecursionPolicy.SupportsRecursion`) allow the170 owning thread to re-enter. DotNext async locks do not. Async acquisition has no thread owner, so re-entering171 simply waits forever. Look for public locked methods calling other public locked methods, and refactor them into172 lock-taking entry points plus private helpers that assume the lock is held.173- **Thread affinity is gone.** After `await`, the code may continue on another thread. A lock acquired174 asynchronously can be released from any thread. Don't keep thread-local or `[ThreadStatic]` assumptions inside the critical section.175- **`AsyncLock.AcquireLockAsync(obj)` restrictions.** It throws `InvalidOperationException` for `ReaderWriterLockSlim`,176 `WaitHandle` and `ReaderWriterLock` instances, and for objects on the runtime's frozen (non-GC) heap such as177 string literals. Never lock on strings. For `SemaphoreSlim`, `AsyncExclusiveLock`, `AsyncReaderWriterLock`178 and `AsyncSharedLock` it uses the object itself as the lock. When in doubt, use an explicit `AsyncExclusiveLock` field.179- **Don't keep `lock` on sync paths that share state with async ones.** If a code path is purely synchronous and hot,180 it may be tempting to keep `lock` there. That is only safe if no async path touches the same state. Otherwise, use181 the sync API of the new lock (step 3).182- **Upgradeable read locks.** `ReaderWriterLockSlim.EnterUpgradeableReadLock` keeps the read lock while waiting for the183 upgrade. `AsyncReaderWriterLock` upgrades by releasing the read lock first, so other writers may run in between. A failed184 `TryUpgradeToWriteLock()` / `TryUpgradeToWriteLockAsync()` leaves the caller holding nothing. Re-validate the state185 you read before the upgrade.186- **Performance trade-off.** Async locks don't block threads while waiting, which improves throughput under contention,187 at the cost of higher latency per acquisition than `lock`. For short, fully synchronous critical sections that never188 share state with async code, `lock` remains faster.