C# Async Coordination: Cancellation, Timeouts, and Bounded Concurrency
Separate cancellation, waiting timeouts and concurrency limits.
Three separate questions for async code: can the caller ask the work to stop (cancellation), how long may it wait (timeout), and how much may run at once (bounded concurrency).
At a glance
- Cancellation is cooperative: a
CancellationTokenis only a request, and the work must pass it on or check it. - A timeout limits waiting:
Task.WaitAsync(TimeSpan)gives up with aTimeoutException, but the task keeps running. CreateLinkedTokenSourcecombines the caller's token with a time budget (a token source with a timeout, orCancelAfter) that the work itself observes.Task.WhenAlldoes not limit concurrency; aSemaphoreSlimorParallel.ForEachAsyncdoes.- Acquire the semaphore outside
tryand release it infinally, so a permit is returned exactly once.
Which tool answers which question
| Question | Tool | It does not |
|---|---|---|
| Can the caller stop the work? | A CancellationToken, passed all the way down to the I/O | Stop code that never checks it |
| How long may I wait? | WaitAsync(timeout) | Stop the work it waited for |
| How long may the work run? | A linked token with CancelAfter | Return on time if the work ignores the token |
| How many calls at once? | SemaphoreSlim, Parallel.ForEachAsync with MaxDegreeOfParallelism | Limit other requests unless it is shared |
A timeout is not a cancellation
// A timeout stops the waiting, not the work.
var workDone = new TaskCompletionSource(); // stands in for work that is still running
Task work = workDone.Task;
try { await work.WaitAsync(TimeSpan.FromMilliseconds(50)); }
catch (TimeoutException) { Console.WriteLine($"WaitAsync timed out; work still running: {!work.IsCompleted}"); }
workDone.SetResult(); // the work finishes later
await work;
Console.WriteLine($"after the work finished: {work.IsCompletedSuccessfully}");
// Link the caller's token with a separate time budget, and keep both sources to see which fired.
using var callerCts = new CancellationTokenSource();
using var budgetCts = new CancellationTokenSource(TimeSpan.FromMilliseconds(100));
using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(callerCts.Token, budgetCts.Token);
try { await Task.Delay(Timeout.Infinite, linkedCts.Token); }
catch (OperationCanceledException)
{
Console.WriteLine($"canceled: caller asked {callerCts.IsCancellationRequested}, time budget expired {budgetCts.IsCancellationRequested}");
}WaitAsync timed out; work still running: True after the work finished: True canceled: caller asked False, time budget expired True
- The work went on after
WaitAsyncgave up. If it holds a connection or uses a quota, give it a token it observes as well. - Keeping the caller's source and the budget's source separate tells a caller who left apart from your own time budget; the linked token alone cannot. If both are canceled, the flags do not say which came first.
Bound the number of calls
using var gate = new SemaphoreSlim(4); // at most 4 calls at once
object countLock = new();
int active = 0, maxActive = 0;
var tasks = Enumerable.Range(1, 10).Select(async i =>
{
await gate.WaitAsync(); // outside try: release only what was acquired
lock (countLock) { active++; maxActive = Math.Max(maxActive, active); }
try
{
await Task.Delay(50); // stands in for the dependency call
return i * 10;
}
finally
{
lock (countLock) active--;
gate.Release();
}
});
int[] results = await Task.WhenAll(tasks);
Console.WriteLine($"{results.Length} calls, never more than 4 at once: {maxActive <= 4}, total {results.Sum()}");10 calls, never more than 4 at once: True, total 550
- The count can be lower than four when calls finish before others start; the gate guarantees only the upper bound. It bounds calls within this one batch. Ten batches at once allow forty calls: protecting a dependency across requests needs a shared limit.
- Pick the limit from the dependency's measured capacity, latency and quota, not from the input size.
- The tasks and results still grow with the input: reject oversized batches at the boundary, or use a bounded queue of workers for large streams.
Parallel.ForEachAsync(items, new ParallelOptions { MaxDegreeOfParallelism = 4, CancellationToken = token }, ...)fits when the work is a plain loop.
Putting it together
A fragment of the usual shape: one budget for the whole operation, shared by the gate and the calls.
var ids = userIds.ToArray(); // enumerate the input before any call starts
using var operationCts = CancellationTokenSource.CreateLinkedTokenSource(requestAborted);
operationCts.CancelAfter(TimeSpan.FromSeconds(3));
using var gate = new SemaphoreSlim(4);
var tasks = ids.Select(async id =>
{
await gate.WaitAsync(operationCts.Token);
try { return await client.GetAsync(id, operationCts.Token); }
finally { gate.Release(); }
});
return await Task.WhenAll(tasks); // join every started call before the gate is disposed- Awaiting
Task.WhenAllkeeps the gate and the token source alive until every call has finished. Copying the input to an array first means enumerating it cannot fail halfway, after some calls have started. - Do not wrap the whole thing in a separate timed wait and dispose the gate early: a call still running would later
Release()a disposed semaphore. - Three seconds here is a cooperative budget: a client that ignores the token can still delay the method.
Common mistakes
- Treating a timed-out
WaitAsyncas stopped work: the task still runs and holds its resources. - Accepting a token and not passing it to the I/O calls: that I/O then cannot respond to cancellation.
- Catching
OperationCanceledExceptionand returning a generic 500: cancellation is expected and should be reported as such. - Starting a task for every item of a large or attacker-controlled list: every call runs at once, and
Task.WhenAlladds no limit. - Releasing the semaphore when
WaitAsyncwas canceled: that adds a permit nobody owned. - Blocking with
.Result,.Wait()orThread.Sleepin async request paths.
In an interview
Why does a timed-out WaitAsync not stop the task? It only ends the wait. The task finishes later unless it observes a cancellation token that is canceled.
Where should the ASP.NET Core request token go? Into a linked token source for the operation, and from there into every call that does the work, down to the actual I/O.
What goes wrong if SemaphoreSlim.Release() is not in finally? A call that throws keeps its permit, so the pool shrinks until later callers wait forever.
How do you choose a concurrency limit? From the dependency's measured capacity and quota, enforced at the right scope: per batch, per instance or shared across the service.
What is the difference between a timeout and a cancellation? A timeout is how long the caller is willing to wait; cancellation is a request to the work to stop. A time budget built with CancelAfter joins the two.
How do you test cancellation without slow sleeps? Hold the fake dependency's calls on a TaskCompletionSource, cancel, assert the state, then release them; no wall-clock waits.
Check yourself
await work.WaitAsync(TimeSpan.FromMilliseconds(50)) throws TimeoutException. What is true of work?
Show answer
Correct answer: B
WaitAsync ends only the wait; the original task carries on until it completes or observes a cancellation.
Option A: Timing out the wait does not cancel the task.
Option C: The TimeoutException belongs to the wait, not to the task.
Option D: Timing out a wait does not dispose the task.
Ten requests each run a batch with its own SemaphoreSlim(4). How many dependency calls can run at once?
Show answer
Correct answer: C
Each batch has its own gate of four, so ten batches allow forty calls; a service-wide limit needs one shared gate or policy.
Option A: Four is the limit of one batch only.
Option B: The count is per call, not per request.
Option D: Each batch is bounded; the total is bounded by the number of batches.
Why is await gate.WaitAsync(token) placed before the try whose finally releases the gate?
Show answer
Correct answer: B
A canceled wait throws before it gets a permit; releasing in that case would add a permit nobody owned.
Option A: Speed is not the reason; the placement decides when a permit may be released.
Option C: It can be called there; the problem is releasing without having acquired.
Option D: SemaphoreSlim is thread-safe either way.
Sources
- Cancellation in managed threads: cooperative cancellation and linked tokens.
- Task.WaitAsync: waiting with a timeout or token.
- CancellationTokenSource.CancelAfter: a time budget.
- SemaphoreSlim:
WaitAsyncandRelease. - Parallel.ForEachAsync: a bounded async loop.
TechInterviewNotes Editorial Team · Updated 28 Nov 2026 ·