Skip to content
Tutorials Center
My learning

Topics

Lesson 98 of 182 ยท Async and Concurrency

WhenAll, WhenAny and Task.WhenEach

Combine tasks in C# - Task.WhenAll, Task.WhenAny, Task.WhenEach, timeouts with WaitAsync, Parallel.ForEachAsync and throttling async work with SemaphoreSlim.

One awaited task is simple. Real programs juggle many: fetch ten web pages, query three services and use whichever answers first, process a thousand files but only five at a time. .NET gives you a small set of task combinators for exactly these patterns. They take several tasks and return one task that represents the group, so you can await the whole thing.

This lesson builds on tasks and async/await. It covers Task.WhenAll (wait for everything), Task.WhenAny (wait for the first), the newer Task.WhenEach (handle results as they arrive), timeouts, Parallel.ForEachAsync, and throttling with SemaphoreSlim. A reminder about our editor: tasks that run at the same time finish in an order that depends on their delays and the scheduler, so examples either use clearly different delays or sort before printing, and the text says whenever order is not guaranteed.

Task.WhenAll: wait for everything

await Task.WhenAll(tasks) completes when every task has completed. For Task<T> the result is an array of the results in the same order as the input, no matter which task finished first.

C# WhenAll keeps the input order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Even though "fast" finishes first, the result array is slow, fast, medium, matching the order of tasks. That makes WhenAll safe to use when you need to line results up with inputs. Note the collection expression [ ... ] for the array, see collection expressions.

When some tasks fail

If one or more tasks fail, WhenAll still waits for all of them, and then throws. await rethrows only the first exception, but the combined task knows about every failure through task.Exception.InnerExceptions.

C# Seeing every failure from WhenAll

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The single catch sees one exception, which one is not worth depending on. The task's Exception.InnerExceptions lists both. If you must handle every error (log them all, say), inspect the stored exceptions instead of relying on catch. Notice that "A ok" still prints: the successful task is not interrupted by its siblings failing.

Task.WhenAny: the first to finish

await Task.WhenAny(tasks) completes as soon as one task completes and returns that task (not its result), so you can look at its status, read its result, and cancel or ignore the rest.

C# First answer wins

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

WhenAny does not cancel the slower tasks. They keep running to completion in the background, burning resources, unless you pass them a CancellationToken and cancel it once you have a winner. Also remember to observe the losers' exceptions if they can fail, or the errors are silently lost.

Processing tasks as they finish

An old pattern calls WhenAny in a loop, removing each finished task from the list. It works, but it is O(n squared) for n tasks and clumsy to write. .NET 9 added Task.WhenEach, which returns an async stream of tasks in completion order.

C# Task.WhenEach streams results as they complete

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The loop body runs once per task, in the order they complete. The delays here are far enough apart (20, 70, 120 ms) that the order is reliable, but when delays are close or tasks do real work, completion order is not guaranteed and you should not depend on it. Each yielded task is already complete, so await done returns at once and rethrows that task's exception if it failed, which lets you handle failures per item. await foreach is explained in Async Streams.

Timeouts

Two clean ways to bound how long you wait.

Task.WaitAsync(TimeSpan) (since .NET 6) returns a new task that throws TimeoutException if the original does not finish in time. It does not stop the original work.

C# WaitAsync with a timeout

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The second way, usually better, is to give the work itself a token that cancels after a time, so the operation really stops. That is the topic of Cancellation and Timeouts. The old-style WhenAny(work, Task.Delay(timeout)) trick still appears in older code; WaitAsync replaces it.

Parallel.ForEachAsync

Parallel.ForEachAsync (.NET 6) runs an async body for each item with a limited degree of parallelism, and returns a task that completes when all items are done. You do not manage tasks yourself.

C# Parallel.ForEachAsync with a degree limit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

At most three bodies run at once. The ConcurrentBag is used because several bodies add results simultaneously; a plain List<int> would not be safe (see concurrent collections). We print with Order() because the completion order is not guaranteed. The token passed to the lambda is cancelled if you pass one in ParallelOptions.CancellationToken or if another iteration throws.

Throttling with SemaphoreSlim

Parallel.ForEachAsync suits a loop. When tasks are started in different places and you want to cap how many do real work at once (for example, to respect an API's rate limit), use a SemaphoreSlim: a counter of available "permits". WaitAsync takes a permit (waiting if none is free) and Release gives it back.

C# Limiting concurrency to two at a time

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Six tasks start immediately, but only two can pass WaitAsync at once, so maxRunning never exceeds 2. Always release in a finally block; forgetting it permanently shrinks the pool. Use SemaphoreSlim, not lock, around code containing await: a lock cannot contain an await at all, and Monitor-based locks are tied to a thread.

Choosing the right tool

Goal Tool
Need every result, in input order await Task.WhenAll(tasks)
Need the first result only await Task.WhenAny(tasks) (then cancel the rest)
Handle each result as soon as it arrives await foreach (var t in Task.WhenEach(tasks))
Bound the waiting time task.WaitAsync(timeout) or a cancellation token
Loop over many items with a limit Parallel.ForEachAsync
Cap concurrency across scattered tasks SemaphoreSlim

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In what order does await Task.WhenAll(tasksOfInt) return its results?

    WhenAll returns an array aligned with the input, regardless of which task finished first.
  2. 2. Three tasks passed to Task.WhenAll fail. What does await throw?

    await unwraps and rethrows a single exception. The full list stays in task.Exception.InnerExceptions.
  3. 3. What does Task.WhenAny return?

    It returns the completed Task itself, so you can inspect its status or await it for the result.
  4. 4. What does WaitAsync(TimeSpan) do when the timeout elapses?

    WaitAsync only stops waiting. To really stop the work, give the operation a cancellation token.
  5. 5. A SemaphoreSlim(3) guards async work. How many callers can be inside at the same time?

    The initial count is the number of permits. A fourth caller waits until one is released.

Summary

  • Task.WhenAll waits for all tasks, returns results in input order, and records every failure while await rethrows just one.
  • Task.WhenAny returns the first completed task but does not cancel the others.
  • Task.WhenEach (.NET 9) yields tasks in completion order; do not rely on that order when timings are close.
  • WaitAsync(timeout) bounds waiting but does not stop the work; use a cancellation token for that.
  • Parallel.ForEachAsync and SemaphoreSlim limit how many async operations run at once; always release permits in finally.

Next: Cancellation and Timeouts