A dashboard can load a profile, prices, and stock independently. If two lookups fail, logging only the exception caught around await Task.WhenAll(...) can hide part of the incident. A successful stock lookup can still be useful, provided the application explicitly allows a partial response.
This tutorial joins a fixed set of tasks, reports every fault, and retrieves only successful child results. It then tests how cancellation changes the batch state. The examples use only the BCL and target .NET 10 with its default C# 14 language version. Both complete programs were compiled and their exact output asserted in an isolated offline container on 4 November 2026. See Microsoft’s language-version defaults.
Separate batch completion from individual outcomes
Task.WhenAll completes after every supplied task finishes. A faulted child makes the batch faulted; otherwise, any canceled child makes it canceled; otherwise it succeeds. The batch retains the collected faults. When all children succeed, the generic overload returns values in input-task order. These are the documented WhenAll rules.
Awaiting a faulted task surfaces one exception, so one catch execution is not an inventory of failures. Keep the returned batch task and inspect its exception collection after observing completion. Microsoft’s async exception explanation describes the difference between stored exceptions and the exception rethrown by await.
Reproduce incomplete reporting, then retain the successful result
Create a console project with dotnet new console --framework net10.0. Replace Program.cs with this complete program and run dotnet run. Run the two programs in this article separately.
The completion sources represent three lookups without using a network or timing-sensitive sleeps. Two fault while stock is still pending. The assertion before completing stock checks that the batch has not finished early. The catch counts the single exception observed by await; the correction follows it: inspect the saved batch and retain the original named child tasks.
using System;
using System.Linq;
using System.Threading.Tasks;
class Program
{
static readonly TimeSpan Limit = TimeSpan.FromSeconds(5);
static void Require(bool condition, string message)
{
if (!condition) throw new InvalidOperationException(message);
}
static async Task Round(bool print)
{
var first = new TaskCompletionSource<int>();
var second = new TaskCompletionSource<int>();
var third = new TaskCompletionSource<int>();
string[] names = { "profile", "prices", "stock" };
Task<int>[] tasks = { first.Task, second.Task, third.Task };
Task<int[]> batch = Task.WhenAll(tasks);
first.SetException(new InvalidOperationException("profile failed"));
second.SetException(new InvalidOperationException("prices failed"));
Require(!batch.IsCompleted, "Batch must wait for stock too.");
third.SetResult(42);
int caught = 0;
try { await batch.WaitAsync(Limit); }
catch (InvalidOperationException) when (batch.IsFaulted) { caught++; }
Require(caught == 1, "Expected one catch execution.");
Require(batch.IsFaulted, "Expected a faulted batch.");
string[] failures = batch.Exception!.Flatten().InnerExceptions
.Select(error => error.Message).OrderBy(text => text, StringComparer.Ordinal)
.ToArray();
Require(failures.SequenceEqual(new[] { "prices failed", "profile failed" }),
"A failure was lost.");
Require(tasks.Count(task => task.IsCompletedSuccessfully) == 1,
"Expected one retained success.");
if (print)
{
Console.WriteLine($"Catch executions: {caught}");
Console.WriteLine($"All faults: {string.Join("; ", failures)}");
for (int i = 0; i < tasks.Length; i++)
if (tasks[i].IsCompletedSuccessfully)
Console.WriteLine($"Success: {names[i]}={tasks[i].Result}");
}
}
static async Task Main()
{
for (int i = 0; i < 50; i++) await Round(print: i == 0);
Console.WriteLine("50 rounds: both faults observed; stock retained");
}
}
Expected output:
Catch executions: 1
All faults: prices failed; profile failed
Success: stock=42
50 rounds: both faults observed; stock retained
The two faults have the same exception type deliberately. The test does not depend on which message await selects. Sorting the full collection makes the printed report stable; it does not establish failure chronology. The program repeats the same assertions 50 times.
batch.Exception exposes an AggregateException for the faulted task, as documented by Task.Exception. Here Flatten().InnerExceptions collects the leaf errors. If the application needs to attribute failures to individual lookups, inspect each faulted child and its exception collection using the same input-name mapping, rather than treating batch exception order as identity.
The generic batch does not deliver a partial result array when it faults. The original stock task still holds its own result. Read Result only in the IsCompletedSuccessfully branch shown above. Microsoft’s Result contract explains that reading an incomplete task can block, while reading a faulted or canceled task throws. Once a successful result is available, reading it returns immediately.
Verify fault and cancellation precedence, including cleanup
Replace Program.cs with this second complete program. Its pending operation uses the cancellable Task.Delay overload with an infinite delay. Cancellation ends the wait, and the operation’s finally records cleanup. A completed faulted sibling does not complete the batch while that operation remains pending: the owner must still cancel and observe it.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static readonly TimeSpan Limit = TimeSpan.FromSeconds(5);
static void Require(bool condition, string message)
{
if (!condition) throw new InvalidOperationException(message);
}
static async Task Round(bool includeFault)
{
using var stop = new CancellationTokenSource();
int exits = 0;
async Task<int> Pending()
{
try
{
await Task.Delay(Timeout.Infinite, stop.Token);
return -1;
}
finally { Interlocked.Increment(ref exits); }
}
Task<int> canceled = Pending();
Task<int> other = includeFault
? Task.FromException<int>(new InvalidOperationException("lookup failed"))
: Task.FromResult(7);
Task<int[]> batch = Task.WhenAll(canceled, other);
try
{
Require(!batch.IsCompleted, "Pending sibling was abandoned.");
stop.Cancel();
try { await batch.WaitAsync(Limit); }
catch (InvalidOperationException) when (includeFault && batch.IsFaulted) { }
catch (OperationCanceledException) when (!includeFault && batch.IsCanceled) { }
Require(canceled.IsCanceled && exits == 1, "Cancellation cleanup failed.");
if (includeFault)
{
Require(batch.IsFaulted && batch.Exception!.InnerExceptions.Count == 1,
"Fault must take precedence over cancellation.");
Require(batch.Exception!.InnerExceptions[0].Message == "lookup failed",
"Unexpected batch fault.");
}
else
{
Require(batch.IsCanceled && batch.Exception is null,
"Expected canceled batch without fault exceptions.");
Require(other.IsCompletedSuccessfully && other.Result == 7,
"Cancellation changed the successful sibling.");
}
}
finally
{
stop.Cancel();
try { await canceled.WaitAsync(Limit); }
catch (OperationCanceledException) when (canceled.IsCanceled) { }
}
}
static async Task Main()
{
for (int i = 0; i < 50; i++)
{
await Round(includeFault: true);
await Round(includeFault: false);
}
int[] values = await Task.WhenAll(Task.FromResult(2), Task.FromResult(1))
.WaitAsync(Limit);
Require(values.SequenceEqual(new[] { 2, 1 }), "Result order changed.");
Console.WriteLine("Fault + cancellation: Faulted (50 rounds)");
Console.WriteLine("Success + cancellation: Canceled (50 rounds)");
Console.WriteLine("Cleanup: 100 pending operations exited exactly once");
Console.WriteLine("All success: 2,1 (input order)");
}
}
Expected output:
Fault + cancellation: Faulted (50 rounds)
Success + cancellation: Canceled (50 rounds)
Cleanup: 100 pending operations exited exactly once
All success: 2,1 (input order)
The fault-plus-cancellation case must expose exactly the lookup fault on the batch. The success-plus-cancellation case must be canceled while retaining the successful sibling’s value. Each case runs 50 times and requires exactly one pending-operation exit. The final success case verifies input order explicitly. A canceled child still needs its own status recorded when the batch is faulted; the batch’s fault collection is not a list of canceled operations.
Each observation has a five-second bound using WaitAsync. An unhandled TimeoutException means the test failed. Timing out a wait does not cancel its producer. This fixture’s cleanup requests cancellation of its owned pending operation and observes that operation before disposing the source. These checks verify task states and ownership in a controlled process; they do not test remote rollback or service throughput.
Choose an explicit application policy
For an optional dashboard panel, return a structured response containing successful values, per-input errors, and canceled statuses. For a required set of inputs, collect the errors for diagnostics and let the request fail. The examples catch known fixture exceptions so they can assert outcomes; an application should handle the exception types its own operation contract permits.
Keep task creation inside the ownership design too. A task-returning API can validate arguments synchronously before returning a task, as Microsoft’s async guidance notes. If a later call throws during startup, previously started operations still need an owner to observe them. Materialize a bounded collection once and keep its input identities. A WhenAll join alone is not a concurrency limit.
If your policy requests sibling cancellation after failure, pass a shared or linked token into operations that support it and still await their completion. Follow CancellationToken propagation across application layers to verify that path. For stalled work caused by blocking, see diagnosing an async deadlock. Keep the partial-response decision separate from those mechanisms, and test the chosen policy with both success and failure inputs.