To limit a batch to three asynchronous operations in flight, share one SemaphoreSlim(3, 3) across the batch. Await a permit before starting the operation, and release it in finally after the operation finishes. A canceled wait has acquired nothing, so it must not release a permit.
This tutorial first reproduces a concurrency limit violation without a network service, then verifies the fix and its cancellation paths. The examples use only the base class library.
Verified 4 November 2026. Both complete programs target .NET 10 with its default C# 14 language version and were compiled and run in a pinned Linux SDK container with network access disabled. These are correctness checks, not throughput benchmarks. Microsoft documents the target framework and language defaults.
What the semaphore limits
The initial count is the number of permits available; the maximum count caps how many the semaphore can hold. A successful wait consumes one, and a release returns one. SemaphoreSlim provides an application-local gate. The same instance must surround every operation competing for that limit. Creating a separate three-permit gate inside each operation would give each operation its own allowance.
Task.WhenAll joins tasks; it does not insert a concurrency limit into their bodies. In this example, constructing the task array calls every asynchronous method. Each runs until it reaches an incomplete await, at which point it returns control to its caller. See the WhenAll contract and the await operator behavior. Put admission before the expensive operation; waiting after starting that operation is too late to protect it.
Reproduce twelve admitted items, then cap them at three
Create a console project targeting net10.0 with implicit usings and nullable reference types enabled. Replace Program.cs with this complete program and run it. No NuGet packages are needed. A standard .NET 10 console project uses these settings.
The completion signal holds admitted operations open, making the peak deterministic. With no gate, all twelve enter before the signal is released. With one shared gate, only the first three enter. The signal simulates an unfinished asynchronous operation; it does not simulate a particular server’s overload response.
using System.Threading;
using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(10));
for (int round = 0; round < 25; round++)
{
int unboundedPeak = await RunBatch(false, deadline.Token);
int boundedPeak = await RunBatch(true, deadline.Token);
if (round == 0)
{
Console.WriteLine($"Without gate: peak={unboundedPeak}");
Console.WriteLine($"With gate: peak={boundedPeak}");
}
}
Console.WriteLine("25 rounds: 12 items finished; all 3 permits restored");
static async Task<int> RunBatch(bool bounded, CancellationToken token)
{
const int limit = 3;
using var gate = new SemaphoreSlim(limit, limit);
var finish = new TaskCompletionSource(
TaskCreationOptions.RunContinuationsAsynchronously);
object sync = new();
int active = 0, peak = 0, completed = 0;
Task[] tasks = Enumerable.Range(0, 12).Select(_ => Work()).ToArray();
Task all = Task.WhenAll(tasks);
try
{
// Work runs to its first incomplete await before returning a task.
int expected = bounded ? limit : 12;
lock (sync)
{
if (active != expected || peak != expected)
throw new Exception("Unexpected number of admitted items");
}
}
finally
{
finish.TrySetResult();
await all;
}
if (active != 0 || completed != 12 || gate.CurrentCount != limit)
throw new Exception("Work or permit leaked");
return peak;
async Task Work()
{
if (bounded)
await gate.WaitAsync(token);
try
{
lock (sync)
{
active++;
peak = Math.Max(peak, active);
}
try
{
await finish.Task.WaitAsync(token);
Interlocked.Increment(ref completed);
}
finally
{
lock (sync) active--;
}
}
finally
{
if (bounded) gate.Release();
}
}
}
Expected output:
Without gate: peak=12
With gate: peak=3
25 rounds: 12 items finished; all 3 permits restored
The assertions run 25 ungated batches and 25 gated batches. They check the initial admitted count, completion of all twelve items in each batch, zero active operations at the end, and all three permits restored. A short lock protects only the counters; the awaited work runs outside that lock. The peak measures admitted operations, not a count of dedicated threads.
WaitAsync(token) asynchronously waits for admission. The acquired permit is held across the awaited operation and returned even if that operation throws. Crucially, the wait is outside the try: cancellation before admission must not execute this operation’s Release. The WaitAsync documentation specifies asynchronous entry and cancellation; Release returns a permit.
The ten-second cancellation token bounds the waits in this cooperative test. The finally opens the test signal and drains all tasks before the gate is disposed. Task.WaitAsync(token) cancels the wait; it does not cancel the task being waited on. Here, the test itself owns and completes that underlying signal. In an application, pass the token to the actual I/O operation as well.
Check cancellation, faults, and permit ownership
Run the next program separately as Program.cs. Its local Run function is the small wrapper to adapt for real asynchronous work. The surrounding code deliberately occupies the sole permit so cancellation while queued is reproducible.
using System.Threading;
using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(10));
for (int round = 0; round < 50; round++)
{
using var gate = new SemaphoreSlim(1, 1);
await gate.WaitAsync(deadline.Token); // The test owns the sole permit.
using (var queuedToken = CancellationTokenSource.CreateLinkedTokenSource(
deadline.Token))
{
Task queued = Run(_ => throw new Exception("Must not enter"),
queuedToken.Token);
if (queued.IsCompleted) throw new Exception("Expected a queued waiter");
queuedToken.Cancel();
await ExpectCancellation(queued);
}
if (gate.CurrentCount != 0)
throw new Exception("Canceled waiter released an unowned permit");
bool entered = await gate.WaitAsync(0, deadline.Token);
if (entered) throw new Exception("A full gate admitted another item");
// A false result acquired nothing: do not call Release for that wait.
gate.Release(); // Release only the test's original permit.
try
{
await Run(_ => Task.FromException(
new InvalidOperationException("work failed")), deadline.Token);
throw new Exception("Expected the work fault");
}
catch (InvalidOperationException ex) when (ex.Message == "work failed") { }
if (gate.CurrentCount != 1) throw new Exception("Fault leaked a permit");
using (var activeToken = CancellationTokenSource.CreateLinkedTokenSource(
deadline.Token))
{
Task active = Run(ct => Task.Delay(Timeout.Infinite, ct),
activeToken.Token);
if (gate.CurrentCount != 0) throw new Exception("Work did not enter");
activeToken.Cancel();
await ExpectCancellation(active);
}
if (gate.CurrentCount != 1)
throw new Exception("Cancellation inside work leaked a permit");
await Run(_ => Task.CompletedTask, deadline.Token);
if (gate.CurrentCount != 1) throw new Exception("Successful work leaked");
async Task Run(Func<CancellationToken, Task> work, CancellationToken token)
{
await gate.WaitAsync(token);
try
{
await work(token);
}
finally
{
gate.Release();
}
}
}
Console.WriteLine("50 rounds: queued cancellation acquired no permit");
Console.WriteLine("50 rounds: zero-timeout wait returned false");
Console.WriteLine("50 rounds: fault, active cancellation and success restored the permit");
static async Task ExpectCancellation(Task task)
{
try
{
await task;
throw new Exception("Expected cancellation");
}
catch (OperationCanceledException) { }
}
Expected output:
50 rounds: queued cancellation acquired no permit
50 rounds: zero-timeout wait returned false
50 rounds: fault, active cancellation and success restored the permit
Each of 50 rounds verifies five paths. Canceling a queued waiter leaves the original owner’s permit held. A zero-timeout acquisition returns false while the gate is full. A work exception, cancellation after admission, and a successful operation each restore the permit. The work body’s infinite delay observes its cancellation token, as specified by Task.Delay. Unexpected results throw instead of printing a passing result.
The zero-timeout overload is useful when the caller wants an immediate busy result. A positive acquisition timeout can instead wait for capacity for a limited interval. In either case, only a true result owns a permit; cancellation throws OperationCanceledException. These are distinct WaitAsync outcomes. An acquisition timeout limits time spent waiting for admission, not the duration of work that has already entered.
Apply the wrapper without changing its ownership rules
- Choose the limit from the resource you are protecting and validate it for your workload. Share the gate across that resource’s intended scope. A gate per request cannot enforce a combined limit across requests.
- Pass the cancellation token both to admission and to the work. Cancellation is cooperative: code that ignores the token can continue holding its permit.
- Keep one release for each successful acquisition. The two-argument constructor makes an over-release beyond the maximum fail with
SemaphoreFullException, but it cannot prove ownership or catch every incorrect release. SemaphoreSlim does not track task identity. - Wait for owners and waiters to finish before disposal. The class documentation excludes
Disposefrom concurrent use with other members.
The last two rules follow from the SemaphoreSlim ownership and thread-safety contract and Release exception behavior. Do not depend on FIFO admission; the API does not promise an entry order.
This pattern bounds work inside the protected region. It still creates a task per input item in the first example, so it does not bound the memory used by a very large pending batch. It also does not enforce requests per second or coordinate limits across application processes. Those require a design beyond this small shared gate.
For the adjacent lifecycle rules, continue with C# Station’s CancellationToken propagation across application layers and Task.WhenAll partial failure handling. They explain how to carry cancellation into real work and inspect failures after the batch has drained.