Skip to content

2.12 — Task vs ValueTask, WhenAll, WhenAny, Task.Run

← Roadmap · Section: 2. Collections, LINQ and Async Prev: 2.11 async/await internals · Next: 2.13 Async deadlocks

Markers: ⭐ 💻 · Confidence: 🔴 · Last reviewed: —


TL;DR

  • Task.WhenAll runs several operations at once and waits for all. It is the single biggest easy performance win in async code.
  • Task.WhenAny returns as soon as the first one finishes — use it for timeouts and racing.
  • ValueTask avoids an allocation when a method usually completes immediately. Only reach for it after measuring, and never await it twice.

The concept

An await on its own is sequential. Three awaits in a row means waiting three times, one after another:

var a = await GetAAsync();     // 200 ms
var b = await GetBAsync();     // 200 ms
var c = await GetCAsync();     // 200 ms
// Total: 600 ms

Each one starts only after the previous finished. But if they do not depend on each other, that is wasted time — you could have had all three in flight at once.

A picture: putting a kettle on, then toast in the toaster, then eggs on the hob. You do not stand and watch the kettle boil before touching the toaster. You start all three and then collect them as they finish. Task.WhenAll is exactly that.

var taskA = GetAAsync();       // started
var taskB = GetBAsync();       // started
var taskC = GetCAsync();       // started — all three running now

await Task.WhenAll(taskA, taskB, taskC);
// Total: 200 ms — the slowest one, not the sum

Three times faster for a two-line change. This comes up in interviews constantly because it is such a common missed optimisation in real code.


How it works

Task.WhenAll

public async Task<Dashboard> LoadAsync(Guid userId, CancellationToken ct)
{
    // Start them all. Note: NO await on these lines — that is the point.
    var ordersTask   = _orders.GetForUserAsync(userId, ct);
    var profileTask  = _users.GetProfileAsync(userId, ct);
    var messagesTask = _messages.GetUnreadAsync(userId, ct);

    await Task.WhenAll(ordersTask, profileTask, messagesTask);

    // Now retrieve the results — these are already complete, so no waiting
    return new Dashboard(
        await ordersTask,
        await profileTask,
        await messagesTask);
}

The critical detail: do not await on the lines that start the tasks. Writing var orders = await _orders.GetForUserAsync(...) makes it sequential again. The tasks must be started first and awaited afterwards.

There is a typed version that returns an array of results:

var results = await Task.WhenAll(ids.Select(id => FetchAsync(id, ct)));
// results is T[] in the same order as the input

⚠️ Do not fire off unbounded WhenAll over a large collection. A thousand simultaneous HTTP calls will exhaust connections and probably get you rate-limited. Batch it:

// Limit to 10 at a time
var throttle = new SemaphoreSlim(10);

var tasks = ids.Select(async id =>
{
    await throttle.WaitAsync(ct);
    try   { return await FetchAsync(id, ct); }
    finally { throttle.Release(); }
});

var results = await Task.WhenAll(tasks);

Or in .NET 6+, Parallel.ForEachAsync does this for you — see 2.19.

Task.WhenAll and exceptions

If several tasks fail, WhenAll throws only the first exception when you await it. The rest are still there, on the returned task:

var all = Task.WhenAll(t1, t2, t3);
try
{
    await all;                     // throws only the FIRST exception
}
catch (Exception)
{
    // Get them ALL from the task itself
    foreach (var ex in all.Exception!.InnerExceptions)
        _logger.LogError(ex, "Task failed");
}

Also worth knowing: WhenAll waits for every task even if one fails early. It does not cancel the others. If you want that, pass a linked CancellationTokenSource.

Task.WhenAny — first one wins

var work    = DoWorkAsync(ct);
var timeout = Task.Delay(TimeSpan.FromSeconds(5), ct);

var finished = await Task.WhenAny(work, timeout);

if (finished == timeout)
    throw new TimeoutException("Took longer than 5 seconds");

var result = await work;      // await again to get the value or rethrow

⚠️ WhenAny does not cancel the losers. In the example above, DoWorkAsync keeps running after the timeout — it just goes unobserved. Always pass a CancellationToken so you can actually stop it.

Note that .NET 6 added a much simpler way to do exactly this timeout:

await work.WaitAsync(TimeSpan.FromSeconds(5), ct);   // throws TimeoutException

Prefer that. WhenAny is for genuine racing — querying three mirrors and taking whichever answers first.

Task vs ValueTask

Task is a class, so returning one allocates an object on the heap. For a method called millions of times that usually completes immediately, those allocations add up.

ValueTask is a struct. When the result is already available, no allocation happens at all.

public ValueTask<User> GetUserAsync(Guid id)
{
    if (_cache.TryGetValue(id, out var cached))
        return new ValueTask<User>(cached);      // NO allocation — the common path

    return new ValueTask<User>(LoadFromDbAsync(id));   // wraps a real Task
}

The rules for ValueTask, and these are strict:

Rule Why
Await it only once The underlying object may be recycled after the first await
Do not use .Result or .Wait() Undefined behaviour on an incomplete ValueTask
Do not pass it to WhenAll/WhenAny Call .AsTask() first
Do not store it in a field Same recycling problem
var vt = GetUserAsync(id);
var a = await vt;
var b = await vt;      // UNDEFINED BEHAVIOUR — may throw or return garbage

If you need any of the forbidden things, call .AsTask() once and use that.

When to use each:

  • Task — the default. Always correct, easy to reason about.
  • ValueTask — only when a method is very hot and usually completes synchronously, and you have measured a real benefit. It is a library-author optimisation, not something to sprinkle through application code.

Task.Run

Covered in 2.10, but the summary:

await Task.Run(() => HeavyComputation());   // CPU-bound: reasonable
await Task.Run(() => http.GetAsync(url));   // I/O: WRONG — just await it directly

Task.FromResult and friends

For returning an already-known value from a method with an async signature:

public Task<int> GetAsync() => Task.FromResult(42);
public Task DoNothingAsync() => Task.CompletedTask;      // no allocation, cached
public Task<int> FailAsync() => Task.FromException<int>(new InvalidOperationException());

Task.CompletedTask is a cached singleton — always use it rather than Task.FromResult<object>(null).


Code

The realistic before-and-after, and the shape to recognise in a code review:

// BEFORE — 3 sequential round trips. ~600 ms.
public async Task<OrderPageModel> GetPageAsync(Guid id, CancellationToken ct)
{
    var order    = await _orders.GetAsync(id, ct);           // 200 ms
    var customer = await _customers.GetAsync(order.CustomerId, ct);  // 200 ms
    var related  = await _orders.GetRelatedAsync(id, ct);    // 200 ms

    return new OrderPageModel(order, customer, related);
}

Look at the dependency: customer needs order.CustomerId, so those two genuinely must be sequential. But related only needs id, which we had from the start.

// AFTER — ~400 ms. The independent call runs alongside the chain.
public async Task<OrderPageModel> GetPageAsync(Guid id, CancellationToken ct)
{
    var relatedTask = _orders.GetRelatedAsync(id, ct);       // start it NOW

    var order    = await _orders.GetAsync(id, ct);           // 200 ms
    var customer = await _customers.GetAsync(order.CustomerId, ct);  // 200 ms

    return new OrderPageModel(order, customer, await relatedTask);   // already done
}

The technique: look at each await and ask "does this actually need the previous result?" Anything that does not can be started earlier.

⚠️ One caveat specific to EF Core: a single DbContext cannot run two queries at the same time. Doing so throws "A second operation was started on this context instance". If the parallel calls share a context, you need separate contexts via IDbContextFactory. See 13.2.


Interview questions

Q: How do you run several async operations concurrently?

Start them without awaiting, then await them together with Task.WhenAll. The mistake is writing var a = await FooAsync() on each line, which makes them sequential — each one only starts after the previous finished. If you capture the tasks first and await afterwards, they all run at once and the total time is the slowest one rather than the sum. For three 200-millisecond calls that turns 600 milliseconds into 200.

Q: What happens to exceptions with Task.WhenAll?

Awaiting the combined task rethrows only the first exception, which is easy to miss if several tasks failed. The others are still available through the Exception property on the task itself, which is an AggregateException holding all of them. So if I need to log everything, I keep a reference to the combined task and inspect InnerExceptions in the catch block. Worth adding that WhenAll waits for every task even after one fails — it does not cancel the rest.

Q: What is ValueTask and when would you use it?

Task is a class, so returning one allocates. ValueTask is a struct, so a method that usually has its result already — a cache hit, a buffered read — can return without allocating. The trade-off is a set of strict rules: you may only await it once, you must not block on it, and you cannot pass it to WhenAll without calling AsTask first, because the underlying object may be pooled and reused after the first await. It is a library-level optimisation for genuinely hot paths, and I would only introduce it after profiling showed the allocations mattered.

Q: How do you put a timeout on an async operation?

In .NET 6 and later, task.WaitAsync(timespan), which throws a TimeoutException if it takes too long. Before that, the pattern was Task.WhenAny with a Task.Delay and then checking which one won. The important caveat with either approach is that timing out does not stop the underlying work — it carries on running unobserved. So you also want to pass a CancellationToken that you cancel, otherwise you have a timeout that frees the caller but leaks the operation.


Traps ⚠️

  • await on the line that starts each task makes them sequential. Capture the tasks first, await afterwards.
  • WhenAll rethrows only the first exception. Inspect task.Exception.InnerExceptions for the rest.
  • WhenAll does not cancel remaining tasks when one fails. They all run to completion.
  • WhenAny does not cancel the losers. Pass a CancellationToken or they leak.
  • Awaiting a ValueTask twice is undefined behaviour. So is blocking on one.
  • Unbounded WhenAll over a large collection exhausts connections. Throttle with SemaphoreSlim or use Parallel.ForEachAsync.
  • Two concurrent queries on one DbContext throw. Use IDbContextFactory for parallel database work.
  • An unobserved failed task used to crash the process. It no longer does by default, but the exception is silently swallowed — which is arguably worse.


Sources