Skip to Content
TUtilityAsync coordination and concurrency

Async coordination and concurrency

On this page

Share two permits across six operations

Install TUtility.Core, put this complete program in Program.cs and run dotnet run. Six tasks share one WaitLock, allowing at most two tasks into the processing section. Results are sorted by job number so output does not depend on completion order.

using System.Collections.Concurrent; using TUtility; using var gate = new WaitLock(maxCount: 2); using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(5)); var completed = new ConcurrentBag<int>(); var tasks = Enumerable.Range(1, 6).Select(ProcessAsync).ToArray(); await Task.WhenAll(tasks); Console.WriteLine($"Completed: {string.Join(", ", completed.OrderBy(x => x))}"); /// <summary>等待成功后处理一个任务;处理成功、失败或取消都释放本次许可。</summary> async Task ProcessAsync(int job) { await gate.WaitAsync(cancellation.Token); try { await Task.Delay(20, cancellation.Token); completed.Add(job); } finally { gate.Release(); } }

Expected output:

Completed: 1, 2, 3, 4, 5, 6

Keep WaitAsync outside try: cancellation while waiting acquires no permit and requires no Release. Dispose the gate after Task.WhenAll finishes every user. Pass cancellation onward when replacing Task.Delay.

Large inputs: bound scheduled tasks as well as active work

Permits bound active operations, not waiting tasks or their data. Creating every task up front still retains the full workload in memory.

This independent program schedules batches of four with two shared permits. Each batch finishes before the next is enumerated; results accumulate only a count and checksum:

using TUtility; using var gate = new WaitLock(maxCount: 2); using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(5)); var jobs = Enumerable.Range(1, 8); var batches = 0; var processed = 0; var checksum = 0; foreach (var batch in jobs.Chunk(4)) { cancellation.Token.ThrowIfCancellationRequested(); var values = await Task.WhenAll(batch.Select(ProcessBoundedAsync)); batches++; processed += values.Length; checksum += values.Sum(); } Console.WriteLine($"Batches: {batches}, processed: {processed}, checksum: {checksum}"); Console.WriteLine($"Permits restored: {gate.CurrentCount == 2}"); /// <summary>单项处理受共享许可约束,调用方等待整批收尾后才调度下一批。</summary> async Task<int> ProcessBoundedAsync(int job) { await gate.WaitAsync(cancellation.Token); try { await Task.Delay(10, cancellation.Token); return job; } finally { gate.Release(); } }

Expected output:

Batches: 2, processed: 8, checksum: 36 Permits restored: True

Chunk accepts synchronous IEnumerable<T> input; use a bounded buffer for async sources. Use independent clients for concurrent database operations; see TORM lifetime.

Task.WhenAll waits for the whole batch; one failure does not cancel siblings. This example stops later batches after failure without rolling back completed external operations. To stop early, cancel the shared token and await each operation.

The slowest item delays the next batch. Use a bounded queue and fixed consumers when continuous scheduling is needed.

Choose by waiting behavior

RequirementEntry pointCaller responsibility
Wait for capacity without per-call cancellationAsyncConcurrencyLimiter.WaitAsync()Await the ValueTask once; release after acquisition
Cancel a waitWaitLock.WaitAsync(token)Cancellation throws; do not release an unacquired permit
Wait within a time budgetWaitLock.WaitAsync(millisecondsTimeout, token)Check bool; release only when true
Tell a consumer to check its queueAsyncAutoResetEventKeep the actual work count in the queue

AsyncConcurrencyLimiter

AsyncConcurrencyLimiter(maxCount) limits concurrent operations. Its current WaitAsync() has no cancellation parameter. Release once in finally after successful acquisition:

using TUtility; using var limiter = new AsyncConcurrencyLimiter(4); await limiter.WaitAsync(); try { Console.WriteLine("Permit acquired."); } finally { limiter.Release(); }

Operations share one limiter instance. Disposal ends queued waiting without awaiting active business work.

Consume the returned ValueTask once. Never abandon a pending acquisition after an outer timeout: a permit acquired later may otherwise be leaked.

Cancellable waiting

Use the SemaphoreSlim-based WaitLock to set an individual wait budget. This standalone fragment waits at most 100 milliseconds to acquire a permit:

using TUtility; using var gate = new WaitLock(maxCount: 1); using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(5)); var acquired = await gate.WaitAsync(millisecondsTimeout: 100, cancellationToken: cancellation.Token); if (!acquired) { Console.WriteLine("No permit within the wait budget."); } else { try { Console.WriteLine("Exclusive operation."); } finally { gate.Release(); } }

WaitAsync(millisecondsTimeout, token) returns a Boolean. Release only after successful acquisition. Waited, Waiting and CurrentCount are observations rather than proof of ownership. Finish users before disposing the gate.

Auto-reset signals

AsyncAutoResetEvent exposes WaitOneAsync(), cancellation / timeout overloads and Set(). A signal normally wakes one waiter. Signals stored without waiters merge, making this suitable for “work is available” notifications rather than counting individual messages.

After waking, check the actual queue or state and drain available work. SetAll() broadcasts a wake-up but does not implement worker shutdown or cleanup.

Pooled async tasks

TUtility.PooledAwait provides pooled task builders, requiring single consumption and correct return to the pool. Use it only in performance hotspots whose callers can meet these constraints.