/dotnext-skills:dotnext-threadingfrom .NEXT
Provides async synchronization primitives from DotNext.Threading: exclusive/reader-writer locks, reset events, countdown event, barrier, trigger, and WaitHandle/CancellationToken awaiting. Use when converting lock/Monitor or ReaderWriterLockSlim to async.
Ships in .NEXT. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
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.All types live in the DotNext.Threading namespace or nested namespaces.
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 callerAsyncReaderWriterLock 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.AsyncAutoResetEvent or AsyncManualResetEvent for signal-based synchronization in async code, or as async-friendly replacement of System.Threading.AutoResetEvent or System.Threading.ManualResetEvent classes.AsyncCountdownEvent if you need async-friendly replacement of System.Threading.CountdownEvent class.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.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).
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.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.await AsyncBridge.WaitAsync(CancellationToken, bool) to replace CancellationToken.WaitHandle.WaitOne() synchronous calls to wait for the cancellation in async methodsawait AsyncBridge.WaitAsync(WaitHandle, TimeSpan, CancellationToken) or await AsyncBridge.WaitAsync(WaitHandle, CancellationToken) to replace WaitHandle.WaitOne() variations of synchronous calls in async methodsQueuedSynchronizer<T> as a base classConsider rules when using these primitives.
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.
await ...; try { } finally { Release(); } pattern.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.CancellationToken parameter and flow it into every acquisition.Monitor.TryEnter(obj, timeout) → TryAcquireAsync(timeout) (returns bool).
AcquireAsync(timeout) throws TimeoutException instead.IDisposable, dispose the new primitive there, preferably via IAsyncDisposable.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();
}
}
bool and never throw on timeout or cancellation. A canceled token also returns false.
Check the result every time.await the async overload instead. Blocking thread-pool threads
while async holders need the pool to finish can starve the pool.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.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();
}
Parallel, PLINQ.System.Threading.Channelslock is fine there and faster.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.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.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).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.lock. For short, fully synchronous critical sections that never
share state with async code, lock remains faster.What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub dotnet/dotnext --plugin dotnext-skills4 skills in this plugin
/dotnext-concurrencyConcurrent data structures and allocation-free async building blocks from the DotNext.Threading NuGet package - AsyncLazy, TaskCompletionPipe, reusable ValueTaskCompletionSource, CancellationTokenMultiplexer, AsyncCounter (throttling), AsyncStateTracker, distributed leases, BoundedObjectPool and the SIEVE-based RandomAccessCache (managed and unmanaged-memory variants). Use when replacing Lazy<T> or Lazy<Task<T>> with async initialization; when reducing allocations of TaskCompletionSource, linked CancellationTokenSource or Task.WhenEach in hot paths; when implementing rate limiting, change notification streams, an object pool, an LRU/concurrent cache (including a large cache that puts pressure on GC), or a distributed lease./dotnext-coreCore types from the DotNext NuGet package - Optional<T> and Result<T> monads, Optional JSON serialization (PATCH DTOs with omitted fields), Timestamp, EnumType attribute lookup, ConsoleLifetimeTokenSource, TypeMap/ConcurrentTypeMap, LocalReference and UserData. Use when expressing absent values or errors without exceptions; when distinguishing undefined and null JSON fields; when measuring elapsed time or tracking deadlines; when reading attributes of enum members; when handling console app shutdown (Ctrl+C, SIGTERM) without a generic host; when a dictionary is keyed by System.Type; when a ref field to a ref struct is needed; or when attaching data to objects via ConditionalWeakTable./dotnext-memoryAllocation-free memory routines from the DotNext and DotNext.Unsafe NuGet packages - SpanOwner (safe stackalloc with pooled fallback), BufferWriterSlim (stack-allocated StringBuilder/buffer replacement with string interpolation), PoolingBufferWriter, PoolingArrayBufferWriter, SparseBufferWriter, and the MemoryAllocator abstraction over ArrayPool, plain arrays and unmanaged memory. Use when reducing allocations in .NET hot paths; when stackalloc length comes from input; when replacing StringBuilder, MemoryStream, RecyclableMemoryStream, ArrayBufferWriter or manual ArrayPool rent/return code; or when making the memory allocation strategy configurable.Other plugins' skills for the same job