In C#, why does awaiting three independent service calls one after another take longer than starting all three and awaiting Task.WhenAll?
answer
- when does the work actually start
- await waits, it does not start
- total time: sum vs slowest
- results array in argument order
basics
~20 sCalling an async method starts its work; await only waits for it. Awaiting each call before making the next adds the three durations together, while starting all three first and awaiting Task.WhenAll costs roughly the slowest one.
solid answer
~40 sA C# async method runs until its first incomplete `await` and hands back a task that is already in progress, so the call is what starts the work. `var p = await LoadProfileAsync(); var o = await LoadOrdersAsync();` does not make the second call until the first has finished, so three 300 ms calls take about 900 ms. Writing `var p = LoadProfileAsync(); var o = LoadOrdersAsync(); var r = LoadRecommendationsAsync(); await Task.WhenAll(p, o, r);` puts all three in flight at once and finishes in about 300 ms. After that, `await p` or `p.Result` returns immediately. `Task.WhenAll` does not start anything or add threads; it is a task that completes when every supplied task has. Only do this for calls that are truly independent and do not share an object that forbids concurrent use.
code
csharp · 21 linesusing System.Diagnostics;
var sw = Stopwatch.StartNew();
var p1 = await LoadAsync("profile", 300);
var o1 = await LoadAsync("orders", 300);
var r1 = await LoadAsync("recommendations", 300);
Console.WriteLine($"one by one: {sw.ElapsedMilliseconds / 100 * 100} ms");
sw.Restart();
Task<string> profile = LoadAsync("profile", 300);
Task<string> orders = LoadAsync("orders", 300);
Task<string> recs = LoadAsync("recommendations", 300);
await Task.WhenAll(profile, orders, recs);
Console.WriteLine($"started first: {sw.ElapsedMilliseconds / 100 * 100} ms");
Console.WriteLine($"{profile.Result}, {orders.Result}, {recs.Result}");
static async Task<string> LoadAsync(string what, int ms)
{
await Task.Delay(ms);
return what;
}go deeper
Recall that calling an async method starts its work and await only waits for it. Be able to rewrite three sequential awaits into start-all-then-await-Task.WhenAll.
Explain why the serial version costs the sum and the concurrent one the slowest call, how results come back from Task.WhenAll in argument order, and why no extra threads are involved.
Show judgment about when concurrency is wrong: dependent calls, shared objects that forbid concurrent use, and downstream services that cannot take the extra load.
Discuss where a codebase should default to concurrent composition and how to keep it from turning into unbounded fan-out against shared dependencies.
## What calling an async method does In C#, a method marked `async` that returns `Task` or `Task<TResult>` runs **synchronously** until it reaches an `await` on something that has not finished yet. At that point it returns a task to its caller, and the rest of the method runs later as a continuation. The task the caller receives is therefore **already in progress**: the HTTP request has been sent, the timer is running, the query is on the wire. Microsoft's documentation calls such tasks *hot*. The consequence is easy to miss: **the call starts the work; `await` only waits for it.** Where you put the `await` decides how much of the work overlaps. ## Awaiting one by one Take a dashboard that needs a user's profile, orders and recommendations from three services, each taking about 300 ms: ```csharp string profile = await LoadProfileAsync(userId); string orders = await LoadOrdersAsync(userId); string recs = await LoadRecommendationsAsync(userId); ``` The second call is not made until the first `await` has resumed, and the third waits for the second. Nothing is blocked, since no thread sits idle during the waits, but the calls are **serial**: the page takes about 900 ms, the sum of the three. ## Start first, then await together ```csharp Task<string> profile = LoadProfileAsync(userId); Task<string> orders = LoadOrdersAsync(userId); Task<string> recs = LoadRecommendationsAsync(userId); await Task.WhenAll(profile, orders, recs); ``` All three requests are in flight before the first `await`, so the page takes about as long as the **slowest** call, roughly 300 ms. `Task.WhenAll` itself: - does **not** start the tasks, because they were started by the calls; - does **not** create threads; with naturally asynchronous I/O, no thread is blocked while the requests are pending; - returns a task that completes when **every** supplied task has completed, even if one fails early. ## Reading the results | Way to read | When it fits | Notes | |---|---|---| | `await profile` after `WhenAll` | tasks of different result types | returns at once; the task has already completed | | `profile.Result` after `WhenAll` | same | does not block, because the task is complete | | `string[] all = await Task.WhenAll(a, b, c)` | tasks with the same `TResult` | `Task.WhenAll<TResult>` returns the results **in argument order** | The generic overloads' documentation states the order: the results are in the same order as the tasks were supplied, not the order they finished. ## When not to start them together Starting the calls together is only correct when the calls are **independent**: 1. The second call must not need the first call's result, as with fetching orders for an id the profile returned. 2. The calls must not share an object that forbids concurrent use, such as one database connection or a client documented as not thread-safe. 3. The downstream services must be able to take the extra simultaneous load. For three calls this is trivial; for thousands it needs a concurrency limit, which is a separate decision. ## Failures in brief Because `Task.WhenAll` waits for every task, a failure in one call does not stop the others, and the combined task faults only after all three have finished. `await` on the combined task rethrows one of the failures, and the full set lives on the combined task's `Exception` property. When none fails, the line after `await Task.WhenAll(...)` sees three completed tasks. ## Mistakes that look concurrent but are not - **Awaiting inside the loop that starts the calls.** `foreach (var id in ids) results.Add(await LoadAsync(id));` is still one call at a time; collect the tasks first and await them after the loop. - **Wrapping I/O calls in `Task.Run`.** It adds a thread-pool hop per call and no overlap that the async calls did not already have. - **Enumerating a lazy `Select` twice.** `var tasks = ids.Select(LoadAsync);` starts the calls each time the query is enumerated, so passing it to `Task.WhenAll` and then enumerating it again to read results starts a second round of requests. Materialize it with `ToArray()` first. ## What interviewers look for - That the candidate knows the call, not the `await`, starts the work. - That they can rewrite sequential awaits into start-then-`WhenAll` and read results afterwards. - That they name the condition: independent calls with no shared non-thread-safe state. - That they do not reach for `Task.Run` to get concurrency for I/O calls that are already asynchronous.
- Is reading `profile.Result` after `await Task.WhenAll(profile, orders, recs)` safe?Yes. Once the combined task has completed successfully, every supplied task has completed successfully, so `.Result` returns the value without blocking. `await profile` is equally cheap and keeps the style uniform. If any task had failed, the `await Task.WhenAll` line would have thrown and the `.Result` line would never run.
- Does `Task.WhenAll` run the calls on extra threads?No. It only creates a task that completes when all supplied tasks complete. The overlap comes from making all the calls before the first `await`. With naturally asynchronous I/O, no thread waits while the requests are pending, so three concurrent calls need no more threads than one.
- The orders call needs the customer id that the profile call returns. Can you still use `Task.WhenAll`?Not for that pair: the orders call cannot start until the profile result exists, so await the profile first. Calls that do not depend on it, such as recommendations keyed by the user id you already have, can still start before that await and be awaited together afterwards.
Ordering three dishes from three kitchens: waiting at the first counter until your food is ready before walking to the next takes the sum of the waits; placing all three orders first and then waiting takes as long as the slowest kitchen.
- Task.WhenAll is what starts the tasks running.
- Sequential awaits already run the calls concurrently.
- Task.WhenAll creates one thread per task it waits on.
- Reading .Result after Task.WhenAll has completed can block or deadlock.
- Calls sharing one non-thread-safe object can safely be started together.