Sequential versus concurrent awaits
Sequential versus concurrent awaits
Independent asynchronous operations may overlap when started before either is awaited. Sequential awaits are appropriate when later work depends on earlier results. Task.WhenAll and Task.WhenAny coordinate tasks that have already been obtained; neither automatically makes CPU work parallel.
Examples target the proposed C# 14 / .NET 10 console baseline (one independent Program.cs per example, nullable enabled). Expected outputs are reasoned, not executed. File examples require an authorized disposable environment with a writable temporary directory and no concurrent writers.
Respect dependencies
When the second request requires the first result, awaiting the first is necessary. A completed fake service keeps this example deterministic while preserving the method contract.
using System;using System.Threading.Tasks;int weight = await GetWeightAsync();int cost = await GetCostAsync(weight);Console.WriteLine(cost);static Task<int> GetWeightAsync() => Task.FromResult(3);static Task<int> GetCostAsync(int weight) => Task.FromResult(weight * 2);The second operation cannot be constructed correctly until the weight is available.
Expected output (reasoned, not executed):
6Combine independent results
WhenAll completes after all supplied tasks finish. With successful generic tasks, the result array follows input order rather than completion order. If any supplied task faults, the combined task faults; otherwise cancellation takes precedence over success. The combined task stores the input failures in its Exception property. Await normally propagates one stored exception, not the complete list; retain the combined task if you need to inspect all failures. Do not depend on which exception is propagated when multiple inputs fault.
using System;using System.Threading.Tasks;var stock = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);var price = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);Task<int[]> all = Task.WhenAll(stock.Task, price.Task);price.SetResult(8);Console.WriteLine(all.IsCompleted);stock.SetResult(3);int[] results = await all;Console.WriteLine(string.Join(",", results));The first result is still pending when price finishes. The returned array uses the argument order stock, price.
Expected output (reasoned, not executed):
False3,8Observe the first completed task
WhenAny returns a wrapper task whose result is the completed input task. Await that input to observe its result or failure. Other operations continue unless separately canceled or completed.
using System;using System.Threading.Tasks;var first = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);var second = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);Task<Task<int>> race = Task.WhenAny(first.Task, second.Task);second.SetResult(20);Task<int> winner = await race;Console.WriteLine(await winner);Console.WriteLine(first.Task.IsCompleted);first.SetResult(10);Console.WriteLine(await first.Task);Only the second task is eligible to win at the decision point. The first is completed and observed separately so it is not abandoned.
Expected output (reasoned, not executed):
20False10Common mistakes and edge cases
WhenAny can return a faulted or canceled winner; the wrapper finishing is not proof of success. WhenAll waits for every supplied task even if one fails. Bound concurrency when working over large collections; starting thousands of tasks can overload a service. Do not concurrently mutate shared state or assume a provider supports overlapping operations on one connection.
Practice and recap
Change the WhenAll example so stock is completed with 7 first and price with 9 second. Predict the status before price finishes and the final array. Then explain how a dependency between price and stock changes the design.
Hint: WhenAll waits for every task and preserves input order.
Learning objective: Choose independent task composition. See the accompanying manual practice and knowledge check.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Sequential versus concurrent awaits — knowledge check
Apply the lesson concepts to the following scenarios.
When is sequential await necessary?
What order does successful WhenAll<T> return results in?
Does WhenAny cancel losing tasks?
Why await the input returned by WhenAny?
What happens when one input faults and another remains unfinished in WhenAll?