SkillPilotAI

Task.WhenAll, cancellation and streams

Real apps run several async calls together, stop slow work in the middle and stream data as it arrives. This video covers Task.WhenAll for concurrent calls, CancellationToken for cancellation and timeouts, IAsyncEnumerable for streams, and TaskCompletionSource and PeriodicTimer.

34.1 Why is it used?

  • Independent calls awaited one after another add up their times; started together they take only as long as the slowest one.
  • Users click Cancel and servers abort requests; long work must stop instead of wasting resources.
  • Timeouts protect a page from one slow dependency (show a fallback instead).
  • Streaming lets the consumer process the first item without waiting for the last.
  • Old event-based APIs and repeating jobs need to fit into async/await code.

34.2 The bug: one await after another

C#
using System.Diagnostics;var sw = Stopwatch.StartNew();var profile = await LoadAsync("Profile", 1000);var orders = await LoadAsync("Orders", 1500);var offers = await LoadAsync("Offers", 500);Console.WriteLine(    $"Done in {sw.Elapsed.TotalSeconds:F1}s"); static async Task<string> LoadAsync(    string name, int ms){    await Task.Delay(ms); // fake API call    Console.WriteLine($"{name} loaded");    return name;}
Output
$ dotnet run Sequential.csProfile loadedOrders loadedOffers loadedDone in 3.1s
Why three seconds?
  1. 1.await Profile: 1 s, nothing else runs

  2. 2.Then await Orders: 1.5 s

  3. 3.Then await Offers: 0.5 s

  4. 4.Total = 1 + 1.5 + 0.5 = 3 s

  5. 5.The calls do not depend on each other

Start them together and wait together: Task.WhenAll

34.3 Fix: Task.WhenAll

  • Call LoadAsync three times without await: all three start at that moment.
  • await Task.WhenAll(...) waits for all of them and returns a string[] of results.
  • Offers finishes first, but the array keeps the order the tasks were passed in.
  • Total time is 1.5 s: the slowest call decides it.
C#
using System.Diagnostics;var sw = Stopwatch.StartNew(); var profileTask = LoadAsync("Profile", 1000);var ordersTask = LoadAsync("Orders", 1500);var offersTask = LoadAsync("Offers", 500); string[] all = await Task.WhenAll(    profileTask, ordersTask, offersTask); Console.WriteLine(string.Join(", ", all));Console.WriteLine(    $"Done in {sw.Elapsed.TotalSeconds:F1}s");
Output
$ dotnet run WhenAll.csOffers loadedProfile loadedOrders loadedProfile, Orders, OffersDone in 1.5s

34.4 CancellationToken

  • A CancellationToken is a signal that tells whether someone asked to cancel.
  • Take it as the last parameter of every async method and pass it to every inner call (here Task.Delay(800, ct)).
  • CancellationTokenSource owns the token and is the one that cancels: Cancel() or CancelAfter(timespan).
  • A cancelled awaited call throws OperationCanceledException; catch it at the top.
C#
static async Task GenerateReportAsync(    CancellationToken ct){    for (int page = 1; page <= 5; page++)    {        await Task.Delay(800, ct); // fake work        Console.WriteLine($"Page {page} ready");    }}
C#
using var cts = new CancellationTokenSource();cts.CancelAfter(TimeSpan.FromSeconds(2)); try{    await GenerateReportAsync(cts.Token);}catch (OperationCanceledException){    Console.WriteLine("Report cancelled");}
Output
$ dotnet run Cancel.csPage 1 readyPage 2 readyReport cancelled
The cancellation flow
  1. 1.CancellationTokenSource creates a token

  2. 2.Token passed down to every async call

  3. 3.Cancel() / CancelAfter(2 s) sends the signal

  4. 4.Inner call (Task.Delay) sees it and throws

  5. 5.OperationCanceledException caught: Report cancelled

Cooperative: the method checks the token itself

34.5 Timeouts with a linked token

  • A timeout is just cancellation triggered by time.
  • CreateLinkedTokenSource(ct) makes a source that cancels when the caller cancels OR when its own CancelAfter fires.
  • The when (!ct.IsCancellationRequested) filter confirms it was the timeout, not the caller, and returns a fallback.
  • For a method that takes no token, task.WaitAsync(timeout) adds a timeout from outside.
C#
static async Task<string> GetOffersAsync(    CancellationToken ct){    using var cts = CancellationTokenSource        .CreateLinkedTokenSource(ct);    cts.CancelAfter(TimeSpan.FromSeconds(1));     try { await Task.Delay(3000, cts.Token); }    catch (OperationCanceledException)        when (!ct.IsCancellationRequested)    {        return "No offers (timeout)";    }    return "Offers";}
Output
$ dotnet run Timeout.csNo offers (timeout)

34.6 IAsyncEnumerable + await foreach

  • Collecting 1000 orders into a List makes the user wait for the last one.
  • async IAsyncEnumerable<T> combines await and yield return: each item is produced as soon as it is ready.
  • await foreach processes each item on arrival: 0.5 s, 1.1 s, 1.6 s.
C#
using System.Diagnostics;var t = Stopwatch.StartNew();await foreach (var order in GetOrdersAsync())    Console.WriteLine(        $"{t.Elapsed.TotalSeconds:F1}s: {order}"); static async IAsyncEnumerable<string>    GetOrdersAsync(){    for (int id = 101; id <= 103; id++)    {        await Task.Delay(500); // fake DB read        yield return $"ORD-{id}";    }}
Output
$ dotnet run Stream.cs0.5s: ORD-1011.1s: ORD-1021.6s: ORD-103

34.7 TaskCompletionSource: event to Task

  • Some libraries report results through an event, not a Task (PaymentGateway.PaymentCompleted).
  • TaskCompletionSource<T> gives a Task you complete yourself with TrySetResult / TrySetException / TrySetCanceled.
  • await tcs.Task waits until the event fires.
  • Pass RunContinuationsAsynchronously so the code after await does not run on the event's thread.
C#
var gateway = new PaymentGateway();var tcs = new TaskCompletionSource<string>(    TaskCreationOptions        .RunContinuationsAsynchronously); gateway.PaymentCompleted += status =>    tcs.TrySetResult(status); gateway.StartPayment("ORD-1042");Console.WriteLine("Waiting for bank..."); string result = await tcs.Task;Console.WriteLine($"Payment: {result}");
Output
$ dotnet run Tcs.csWaiting for bank...Payment: ORD-1042 SUCCESS

34.8 PeriodicTimer: work every interval

  • WaitForNextTickAsync returns true on every tick, so the loop runs once per second.
  • The token cancels at 3.5 s: after 3 ticks OperationCanceledException ends the loop.
  • Unlike the old Timer callbacks, ticks never overlap.
C#
using var cts = new CancellationTokenSource(    TimeSpan.FromSeconds(3.5));using var timer = new PeriodicTimer(    TimeSpan.FromSeconds(1));var ct = cts.Token;int tick = 0;try{    while (await timer.WaitForNextTickAsync(ct))        Console.WriteLine($"Tick {++tick}");}catch (OperationCanceledException){    Console.WriteLine("Tracking stopped");}
Output
$ dotnet run Timer.csTick 1Tick 2Tick 3Tracking stopped

34.9 Comparison: the tools

ToolUse it forKey point
Task.WhenAllSeveral independent calls togetherTotal time = slowest call; waits for all
CancellationTokenStopping work on requestCooperative; pass it down
CancelAfter / linked tokenTimeoutsLinked: caller cancel OR timeout
IAsyncEnumerableStreaming large resultsawait foreach, process on arrival
TaskCompletionSourceWrapping events/callbacks as a TaskUse RunContinuationsAsynchronously
PeriodicTimerRepeating work at an intervalNo overlapping ticks, token to stop

34.10 Checkpoint: exceptions in WhenAll

  • Orders and Offers both fail; await WhenAll throws only the first exception (Orders API down).
  • All errors are in the WhenAll task's Exception.InnerExceptions (count 2).
  • Profile still loaded: WhenAll waits for every task to finish.
C#
var all = Task.WhenAll(    LoadAsync("Profile", 1000),    FailAsync("Orders", 300),    FailAsync("Offers", 600)); try { await all; }catch (Exception ex){    Console.WriteLine($"Caught: {ex.Message}");    var errors = all.Exception!.InnerExceptions;    Console.WriteLine($"Total: {errors.Count}");}
Output
$ dotnet run WhenAllError.csProfile loadedCaught: Orders API downTotal: 2

34.11 Common mistakes

  • Taking a CancellationToken but never passing it on: work continues after cancel (all 5 batches exported).
  • Fix: check ct.ThrowIfCancellationRequested() in loops and pass ct to every inner call (stops after batch 2).
  • Awaiting independent calls sequentially instead of starting them first.
  • Myth: Cancel force-kills a task. Cancellation is cooperative; the method stops only when it checks the token.
  • Myth: WhenAll creates threads. The calls already started; WhenAll just waits for them.
C#
static async Task ExportAsync(    CancellationToken ct){    for (int i = 1; i <= 5; i++)    {        await Task.Delay(800);        Console.WriteLine($"Row batch {i}");    }}
C#
static async Task ExportAsync(    CancellationToken ct){    for (int i = 1; i <= 5; i++)    {        ct.ThrowIfCancellationRequested();        await Task.Delay(800, ct);        Console.WriteLine($"Row batch {i}");    }}

34.12 Interview tips

  • Start independent calls first, then await Task.WhenAll: total time equals the slowest call.
  • Every async method takes a CancellationToken as the last parameter and passes it down.
  • Timeouts: CancelAfter on a linked token source, or WaitAsync for APIs without a token.
  • Cancellation is cooperative; await WhenAll surfaces the first exception, the rest are in task.Exception.
  • Stream large results with IAsyncEnumerable; wrap events with TaskCompletionSource.