10.8 · Task groups, async let, cancellation and task locals in practice

The first pass explained what a task tree is. This section is the working detail: how results come back, how you bound the work, what happens to siblings on an error, and what a cancelled task actually does.

Mental model. Children live inside their scope: it waits for them, cancels them when it exits early, and passes them its task-locals, but cancellation is a request that code must notice.

Groups and async let

Completion order, bounded fan-out, errors, discarding groups and unawaited async let.

  1. In what order do task group results arrive, and how do you limit how many children run at once? 10.8.1 · L3
    A task group yields results in completion order, not the order you added the children. Three children that sleep 90, 10 and 50 ms come back as [1, 2, 0]. If…
  2. What happens to the other children when one child in a throwing task group fails, and what does a discarding task group change? 10.8.2 · L5
    In withThrowingTaskGroup an error thrown by a child is rethrown when you try await its result (for try await or next()). If that error then leaves the group’s…
  3. What happens to an async let that you never await when the scope ends? 10.8.3 · L3
    async let starts a child task immediately, bound to the scope that declares it. If the scope exits without awaiting it (an early return, a throw, or simply…

Cancellation and context

Handlers, cooperative checks, sleeping, and task-local values.

  1. How does cancellation actually reach your code: what do checkCancellation, isCancelled, withTaskCancellationHandler and sleeping do, and which calls ignore it? 10.8.4 · L3
    Cancelling a task only sets a flag and runs handlers; nothing is interrupted. Your code notices it by polling (Task.isCancelled, or try…
  2. Which tasks inherit a @TaskLocal value, and when is it a better tool than a parameter? 10.8.5 · L3
    A @TaskLocal value is bound for the dynamic extent of a closure with withValue, and it is inherited by child tasks created inside it: async let, task-group…

More in Concurrency