skip to content

In C# on .NET 9 or later, how does Task.WhenEach let you handle tasks in the order they finish, and what replaced it before?

level: middleimportance: nice to knowfreq 25%

answer

  1. an async stream of tasks
  2. await foreach over completions
  3. failed tasks are yielded too
  4. the older loop and its cost

basics

~20 s

Task.WhenEach, added in .NET 9, returns an IAsyncEnumerable of the input tasks that yields each one as it completes, so await foreach handles them in completion order. Earlier code looped over Task.WhenAny and removed each finished task.

solid answer

~40 s

`Task.WhenEach(tasks)` returns `IAsyncEnumerable<Task>`, or `IAsyncEnumerable<Task<TResult>>` for typed tasks. `await foreach (Task<string> done in Task.WhenEach(loads))` receives each task once it has completed, so the dashboard can render orders as soon as they arrive instead of waiting for all three. WhenEach yields faulted and canceled tasks too and never throws for them; `await done` inside the loop returns the value or rethrows that task's exception, so a try/catch per item keeps one failure from ending the loop. Before .NET 9 the pattern was `while (tasks.Count > 0) { var t = await Task.WhenAny(tasks); tasks.Remove(t); ... }`, which registers a continuation on every remaining task each round, quadratic for large sets. The enumerable is meant to be iterated once.

code

csharp · 30 lines
csharp
Task<string>[] loads =
[
    LoadAsync("profile", 300),
    LoadAsync("orders", 100),
    FailAsync("recommendations", 200),
];

await foreach (Task<string> done in Task.WhenEach(loads))
{
    try
    {
        Console.WriteLine($"ready: {await done}");
    }
    catch (HttpRequestException ex)
    {
        Console.WriteLine($"failed: {ex.Message}");
    }
}

static async Task<string> LoadAsync(string what, int ms)
{
    await Task.Delay(ms);
    return what;
}

static async Task<string> FailAsync(string what, int ms)
{
    await Task.Delay(ms);
    throw new HttpRequestException($"{what} returned 503");
}

go deeper

for a junior

Recall that Task.WhenEach, new in .NET 9, gives you finished tasks one at a time through await foreach.

for a middle

Explain that it yields tasks rather than values, that failed tasks are yielded and rethrow only when awaited, and how the older Task.WhenAny loop did the same job.

for a senior

Point out the single enumeration, cancellation that stops the loop but not the work, and the quadratic cost of the WhenAny loop for large task sets.

for a principal

Decide when per-item streaming is worth the extra error handling compared with one Task.WhenAll, and what a library targeting .NET 8 should do instead.

## The problem it solves `Task.WhenAll` hands you everything at the end; `Task.WhenAny` hands you one winner. Between them sits a common need: **process each result as soon as it is ready**. A dashboard that loads profile, orders and recommendations should render the orders panel the moment orders arrive, not after the slowest service answers. ## Task.WhenEach (.NET 9) .NET 9 added `Task.WhenEach`, with overloads taking `params Task[]`, `params ReadOnlySpan<Task>` or `IEnumerable<Task>`, and generic versions for `Task<TResult>`. It returns an **async stream**: `IAsyncEnumerable<Task>` or `IAsyncEnumerable<Task<TResult>>`. ```csharp await foreach (Task<string> done in Task.WhenEach(loads)) { try { Render(await done); } catch (HttpRequestException ex) { ShowPanelError(ex); } } ``` What the runtime source shows about it: - each input is yielded **once it has completed**; the doc comment adds that the exact order in which tasks become available is not defined, so treat it as completion order, not a sequence to rely on; - the stream yields the **task**, not its value, and it yields faulted and canceled tasks as well, so the loop itself never throws because an input failed; - `await done` on a yielded task returns at once with the value, or rethrows that task's own exception; - the enumerable supports **one** iteration: the implementation comment says every task is yielded only once, and later enumerations are empty; - its iterator takes a `CancellationToken` marked `[EnumeratorCancellation]`, so `.WithCancellation(token)` stops the loop with an `OperationCanceledException`, but it does **not** cancel the tasks themselves. A yielded task that faulted and that you never await stays unobserved, exactly as it would outside the loop. ## What code did before ```csharp var pending = loads.ToList(); while (pending.Count > 0) { Task<string> done = await Task.WhenAny(pending); pending.Remove(done); Render(await done); } ``` This works and is still what a project on .NET 8 writes. Its cost grows badly: Microsoft's guide to consuming task-based APIs notes that each `WhenAny` call registers a continuation on every remaining task, so N tasks create O(N²) continuations over the loop's life. For three panels that is irrelevant; for thousands of tasks it is not. `WhenEach` registers one completion action per task. ## Stopping early `WhenEach` also fits "take the first good answers and stop". Breaking out of the `await foreach` disposes the enumerator, which ends the iteration cleanly, but the tasks that were never yielded are **not** cancelled; they run to completion in the background. The usual shape is: 1. create the tasks with a token from one `CancellationTokenSource`; 2. loop with `await foreach`, `await` each yielded task, and `break` once enough results are in; 3. cancel the source so the remaining work stops, and observe or log what the cancelled tasks report. The typed overloads keep the result type: `Task.WhenEach(loads)` over `Task<string>[]` yields `Task<string>`, so `await done` gives a `string` without casts. ## Choosing a combinator | Need | API | What you get | |---|---|---| | everything, at the end | `Task.WhenAll` | one task; results array for `Task<TResult>` | | the first to finish | `Task.WhenAny` | `Task<Task>` with the winner | | each one as it finishes | `Task.WhenEach` (.NET 9) | `IAsyncEnumerable` of completed tasks | ## Pitfalls to name in an interview 1. Expecting the loop to throw when a task faults. It does not; you must `await` each yielded task or check its status. 2. Assuming argument order. The stream follows completion, not the order of the input array. 3. Enumerating the same `WhenEach` result twice and wondering why the second pass is empty. 4. Treating cancellation of the loop as cancellation of the work. The tasks keep running unless their own tokens are canceled. 5. Reaching for it on a target framework older than .NET 9, where it does not exist; there the `WhenAny` loop or a small completion-order helper is the answer. ## Version note `Task.WhenEach` exists from .NET 9 onward, so .NET 10, the current long-term-support release, has it, while a library that still targets .NET 8 must keep the older loop.

  • What happens if you run `await foreach` twice over the same `Task.WhenEach` result?
    The second pass yields nothing. The implementation hands every task out once, to the first enumeration, and later enumerations end immediately. Store the tasks themselves if you need to look at them again.
  • Does cancelling the loop with `.WithCancellation(token)` cancel the tasks?
    No. The token stops the enumeration, which throws an `OperationCanceledException` at the next wait, but the tasks keep running. To stop the work, pass the same token into the operations that produced the tasks.

  • Task.WhenEach throws as soon as one of its tasks faults.
  • Task.WhenEach yields the tasks in the order they were passed in.
  • Task.WhenEach is already available on .NET 8.
  • A Task.WhenAny loop scales well to thousands of tasks.
  • Cancelling the await foreach also cancels the underlying tasks.

Assumes .NET 10; Task.WhenEach was added in .NET 9, so code targeting .NET 8 still needs a Task.WhenAny loop.