Module 1 · Control Flow, Cancellation, and Time Budgets · Lesson 2 of 12
Timeout Budgets with WaitAsync and Linked Tokens
The caller receives a timeout, yet the dependency later returns 42. Which task ended? Keep the original work task separate from the task returned by WaitAsync. Then compare that wait-only policy with passing a budget token into the work itself.
The console demonstration records timer-driven observations. It does not promise an exact elapsed time, cancellation position or Boolean printout. The provider-aware timeout APIs require .NET 8 or later.
Observe the wait and the work separately
The program below illustrates the three distinctions in this lesson. WaitAsync stops only the waiting. A budget token requests cooperative cancellation of the work. Fresh per-call timeouts add up; a shared budget requests cancellation across the sequence. Timer scheduling is not a hard wall-clock deadline, so the illustrative timings and the call in which cancellation occurs can vary.
// WaitAsync bounds the wait; a token requests that cooperative work stop.
// .NET 8+ console program with implicit usings. Not an executed transcript.
using System.Diagnostics;
int stillRunning = 0;
async Task<int> SlowDependencyAsync(CancellationToken ct)
{
Interlocked.Increment(ref stillRunning);
try { await Task.Delay(300, ct); return 42; }
finally { Interlocked.Decrement(ref stillRunning); }
}
// 1) WaitAsync: the caller stops waiting, the work keeps going.
var work = SlowDependencyAsync(CancellationToken.None);
try { await work.WaitAsync(TimeSpan.FromMilliseconds(50)); }
catch (TimeoutException) { Console.WriteLine($"WaitAsync threw TimeoutException; dependency still running: {stillRunning == 1}"); }
await work; // let it finish so the next measurement is clean
Console.WriteLine($"...and it later completed anyway with {work.Result}");
// 2) Budget token: the work itself is cancelled.
using (var budget = new CancellationTokenSource(TimeSpan.FromMilliseconds(50)))
{
try { await SlowDependencyAsync(budget.Token); }
catch (OperationCanceledException ex) { Console.WriteLine($"Budget token cancelled the work: {ex.GetType().Name}; dependency still running: {stillRunning == 1}"); }
}
// 3) Three sequential calls, each with a fresh 100 ms timeout, vs one shared 150 ms deadline.
async Task<(long Elapsed, int Completed, bool Cancelled)> Sequential(bool freshPerCall, CancellationToken overall)
{
var sw = Stopwatch.StartNew();
int completed = 0;
for (int i = 0; i < 3; i++)
{
using var perCall = freshPerCall ? new CancellationTokenSource(100) : null;
var token = perCall?.Token ?? overall;
try { await Task.Delay(90, token); }
catch (OperationCanceledException) when (token.IsCancellationRequested)
{
return (sw.ElapsedMilliseconds, completed, true);
}
completed++;
}
return (sw.ElapsedMilliseconds, completed, false);
}
var fresh = await Sequential(true, CancellationToken.None);
using var deadline = new CancellationTokenSource(150);
var shared = await Sequential(false, deadline.Token);
Console.WriteLine($"Fresh per-call budgets: completed {fresh.Completed}/3; cancelled={fresh.Cancelled}; elapsed={fresh.Elapsed} ms");
Console.WriteLine($"Shared budget: completed {shared.Completed}/3; cancelled={shared.Cancelled}; elapsed={shared.Elapsed} ms");Expected behavior, not measured output
No exact elapsed time, Boolean printout, or cancellation call number is promised. Timer scheduling, process suspension and thread-pool delays can change outcomes.
- In the usual wait-only timeout path, the caller sees
TimeoutExceptionbutworkcontinues. The laterawait workobserves its completion and any failure. In real code, give abandoned work an explicit owner that observes exceptions and disposes resources; a timeout does not do this for you. - Passing the budget token to
Task.Delaylets that delay cancel cooperatively. Itsfinallyruns before the task completes, decrementing the counter. A remote system can still have processed a request even when local I/O cancels. - Fresh 100 ms budgets allow each 90 ms step to use a new allowance. Three successful steps nominally require 270 ms of delays. A late timer can still cancel a step; the program therefore reports the actual completed count rather than claiming success.
- The single 150 ms budget covers the entire sequence instead of restarting per call. It will commonly interrupt the second delay, but neither that position nor a sub-200 ms return is guaranteed.
- Every per-call source is disposed. Returning only
new CancellationTokenSource(...).Tokenwould lose the owner needed for disposal.
Request cancellation of the underlying operation
public async Task<Quote> GetQuoteAsync(
string sku,
TimeProvider timeProvider,
CancellationToken requestAborted)
{
using var timeout = new CancellationTokenSource(
TimeSpan.FromSeconds(2),
timeProvider);
using var budget = CancellationTokenSource.CreateLinkedTokenSource(
requestAborted,
timeout.Token);
return await pricingClient.GetQuoteAsync(sku, budget.Token);
}The linked source combines caller cancellation with the service's own two-second budget. The dependency must observe budget.Token for the request to stop promptly.
Bound only the wait
var result = await backgroundTask.WaitAsync(
TimeSpan.FromSeconds(2),
requestAborted);If the interval expires, WaitAsync throws TimeoutException; if the token is canceled, it throws cancellation. The original backgroundTask may still be running. This is correct when the work is intentionally shared or cached, but wasteful when it represents a per-request HTTP or database call.
Use one end-to-end budget
Giving three sequential dependency calls their own fresh five-second timeouts can produce a fifteen-second user experience. Start with an end-to-end deadline and allocate smaller dependency budgets within it.
Reserve time for retries and response serialization. A retry policy must stop when the remaining budget cannot accommodate another attempt.
Testing with TimeProvider
Inject TimeProvider and actually pass it to each timer-owning API, for example new CancellationTokenSource(budget, timeProvider) or task.WaitAsync(budget, timeProvider, token). Merely injecting it does not change ordinary real-time APIs. A fake provider lets tests advance virtual time; advance only after the operation has registered its timer. FakeTimeProvider is supplied by the Microsoft.Extensions.TimeProvider.Testing package.
Tests should separately prove caller cancellation, service-budget expiry, successful early completion, wait-only timeout behavior, and resource cleanup.
Operational signals
Report caller cancellation and service timeout separately. They have different owners and remedies. Track dependency name, configured budget, elapsed time, retry count, and whether the underlying call acknowledged cancellation.
The interview-quality answer is concise: WaitAsync limits waiting, a token requests cooperative stopping, and a linked source composes cancellation ownership. Then explain why the underlying operation must receive the token.
Failure modes
WaitAsyncused as "the timeout" for per-request I/O. The connection, memory and remote work stay busy after the user has gone.- Fresh timeouts per step, or per retry. The total latency is the sum of the steps. Derive each step's budget from the time remaining on one deadline.
new CancellationTokenSource(TimeSpan)in code you want to test. It uses the real clock. Use theTimeProvideroverload, as in the snippet above.- Treating
TimeoutExceptionandOperationCanceledExceptionthe same.WaitAsyncsignals its own timeout withTimeoutException; a token signals with cancellation.
Keep the original task in the picture
Write your predictions before opening the checks below.
- What does
task.WaitAsync(TimeSpan.FromSeconds(2))throw when the time runs out, and what happens totask?
- A request has a 3-second SLA and calls A, then B, then C. How should you set the timeouts?
- When is
WaitAsyncthe right tool?
- How do you make
CancelAfter-style budgets testable?
Pause here. Keep the result and the reason separate.
Hint: A wrapper can finish waiting while the underlying operation still needs an owner.
Compare with the contract
TimeoutException.WaitAsyncdoes not cancel the original task, which may still be running.
- One overall budget linked to caller cancellation, with smaller per-call budgets and a reserve for retries and serialization. A linked source combines signals; it does not itself calculate remaining time. Use a monotonic clock/provider to calculate remaining duration when needed, and remember cancellation is cooperative, not an SLA guarantee.
- When the underlying work is shared or cached and should keep running for other callers, so only this caller stops waiting.
- Construct the source with a
TimeProviderand useFakeTimeProviderin tests (see lesson 4).
Check the boundary
backgroundTask.WaitAsync(timeout) throws TimeoutException. What does that establish about backgroundTask?
Show answer
Correct answer: A
WaitAsync bounds waiting and does not cancel or join the underlying task. Its owner must still observe the eventual outcome and protect resources it uses.
Hint: Name the task represented by each awaitable.
TechInterviewNotes Editorial Team · Updated 28 Oct 2026 ·