In C#, you race a slow call against Task.Delay with Task.WhenAny to impose a timeout; what happens to the call that lost, and to any exception it throws later?
answer
- it returns a task, not a value
- the winner may be faulted
- nobody stops the loser
- a token the loser actually watches
basics
~20 sTask.WhenAny only reports which task finished first; it never cancels the others. The losing call keeps running, and if it faults later with nobody awaiting it, its exception goes unobserved. Pass it a CancellationToken and cancel it.
solid answer
~40 s`Task.WhenAny` returns a `Task<Task>` that always ends `RanToCompletion`, with `Result` set to the first input to complete, even if that input faulted or was canceled. So `await Task.WhenAny(call, Task.Delay(200))` never throws: you compare the winner with the delay task and then `await` the winner to get its value or its exception. If the delay wins, `call` is still running; WhenAny has no way to stop it. Its socket, buffers and downstream work stay alive, and if it faults later and nothing observes it, the failure surfaces only through `TaskScheduler.UnobservedTaskException` when the task is finalized. The fix is to give the call a `CancellationToken` from a `CancellationTokenSource` and cancel it when the timeout wins, then observe or await the canceled task so its outcome is handled.
code
csharp · 28 linesusing var cts = new CancellationTokenSource();
Task<string> recs = LoadRecommendationsAsync(cts.Token);
Task timeout = Task.Delay(200);
Task winner = await Task.WhenAny(recs, timeout);
if (winner == timeout)
{
Console.WriteLine($"timed out; recs status: {recs.Status}");
cts.Cancel(); // without this, recs keeps running
}
else
{
Console.WriteLine(await recs);
}
try { await recs; }
catch (OperationCanceledException) { Console.WriteLine($"recs status after cancel: {recs.Status}"); }
Task faulted = Task.FromException(new TimeoutException("boom"));
Task<Task> any = Task.WhenAny(faulted, Task.Delay(1000));
Task first = await any;
Console.WriteLine($"WhenAny status: {any.Status}, winner status: {first.Status}");
static async Task<string> LoadRecommendationsAsync(CancellationToken token)
{
await Task.Delay(1000, token);
return "recommendations";
}go deeper
Recall that Task.WhenAny hands back whichever task finished first, and that you still have to await that task to get its value.
Explain why the returned task always ends RanToCompletion, why a faulted winner does not throw, and how the reference comparison against the delay task works.
Show that you cancel the losing work through a token it honours, observe its outcome, and handle a fast-failing replica winning a first-wins race.
Weigh per-call timeouts against one deadline for a group of calls, and how abandoned work affects downstream capacity during an incident.
## What Task.WhenAny returns `Task.WhenAny` takes two or more tasks and returns a `Task<Task>`, or `Task<Task<TResult>>` for typed inputs. The runtime source's remarks spell out its contract: - the returned task completes when **any** input completes; - it **always** ends in `RanToCompletion`; - its `Result` is the **first input to complete**, even if that input ended `Faulted` or `Canceled`. Two consequences follow. First, `await Task.WhenAny(...)` never throws because an input failed: you get a task back and must inspect or `await` it yourself. Second, `WhenAny` gives you no result value directly; that needs a second await, which is why the idiom `await await Task.WhenAny(...)` exists. ## The timeout idiom ```csharp using var cts = new CancellationTokenSource(); Task<string> recs = LoadRecommendationsAsync(cts.Token); Task timeout = Task.Delay(200); Task winner = await Task.WhenAny(recs, timeout); if (winner == timeout) { cts.Cancel(); // show the dashboard without recommendations } else { string value = await recs; // value, or the call's own exception } ``` The comparison is by reference: `winner` is one of the task objects you passed in. ## What happens to the loser Nothing about `WhenAny` stops the task that lost. When the delay wins: 1. the recommendations call is still `WaitingForActivation`, which is to say still in progress; 2. its connection, buffers and any server-side work continue until it finishes on its own; 3. if it later faults and no code awaits it or reads its `Exception`, the failure is **unobserved**. The runtime raises `TaskScheduler.UnobservedTaskException` only when the faulted task is finalized by the garbage collector, which may be much later or never before the process exits. The same is true in the other direction: when the call wins, the `Task.Delay` timer stays scheduled until it fires. On a hot path that runs this idiom thousands of times, give the delay its own token and cancel it as well. | Situation | What `WhenAny` does | What you must do | |---|---|---| | timeout wins | returns the delay task | cancel the call through its token, then observe the outcome | | call wins, succeeded | returns the call | `await` it for the value; cancel the delay if it matters | | call wins, faulted | returns the faulted call without throwing | `await` it to rethrow, or read `Exception` | ## First-wins across replicas The other classic use is redundancy: send the same query to three replicas and take the first answer. Because `WhenAny` reports the first task to **complete**, a replica that fails fast wins the race. A robust loop removes a faulted winner and calls `WhenAny` again until one succeeds or all have failed, then cancels the rest through a shared `CancellationTokenSource`. Calling `WhenAny` repeatedly over a large set is quadratic in registrations, which matters for many tasks but not for three. ## Observing a loser you abandon Sometimes the losing call cannot be cancelled, for example a third-party method with no token parameter. Abandoning it is then a conscious choice, and its outcome still needs an owner: - attach a continuation that logs faults, such as `call.ContinueWith(t => Log(t.Exception!), TaskContinuationOptions.OnlyOnFaulted)`; - or keep the task in a tracker that a shutdown step awaits; - never just drop the reference, because a later fault then surfaces only through the unobserved-exception event, if at all. ## Cooperative cancellation is the only stop C# tasks cannot be aborted from outside. Cancelling only works if the losing operation was given a `CancellationToken` and passes it down to the I/O it performs. Code that ignores its token runs to completion no matter how many timeouts fire. `Task.WaitAsync(TimeSpan)` is a shorter way to write the timeout, throwing a `TimeoutException`, but it has the same limit: the underlying operation keeps running unless a token stops it. ## Interview angle Interviewers use this to separate "I know the API" from "I know what it does to resources": - does the candidate know `WhenAny` returns a task, not a value, and never throws for the winner; - do they cancel the loser rather than abandoning it; - do they make sure a loser that fails later is still observed or logged.
- Three replicas race and the fastest one faults. What does `await await Task.WhenAny(replicas)` do?It throws that replica's exception, even though the other two may still succeed, because `WhenAny` reports the first task to complete in any state. Loop instead: when the winner is faulted, remove it and call `WhenAny` on the rest, until one succeeds or none remain, then cancel the others.
- Is `call.WaitAsync(TimeSpan.FromMilliseconds(200))` a better timeout than `WhenAny` with `Task.Delay`?It is shorter and throws a `TimeoutException` instead of making you compare tasks, but it has the same limit: only the wait is abandoned. The underlying operation keeps running unless it was given a cancellation token that you cancel.
- Why cancel the `Task.Delay` when the real call wins?The delay task keeps its timer until it fires. Done thousands of times a second, those pending timers add up. Passing the delay its own token and cancelling it when the call wins releases the timer at once.
- Task.WhenAny cancels the tasks that did not finish first.
- await Task.WhenAny throws when the first task to finish has faulted.
- Task.WhenAny returns the result value of the fastest task.
- A timed-out call stops running once the timeout wins the race.
- A loser that faults later crashes the process on modern .NET.