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.
- In what order do task group results arrive, and how do you limit how many children run at once?
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… - What happens to the other children when one child in a throwing task group fails, and what does a discarding task group change?
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… - What happens to an async let that you never await when the scope ends?
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.
- How does cancellation actually reach your code: what do checkCancellation, isCancelled, withTaskCancellationHandler and sleeping do, and which calls ignore it?
Cancelling a task only sets a flag and runs handlers; nothing is interrupted. Your code notices it by polling (Task.isCancelled, or try… - Which tasks inherit a @TaskLocal value, and when is it a better tool than a parameter?
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
- 10.1 · Queues, QoS, barriers, groups, semaphores and sources
- 10.2 · Operation, OperationQueue, dependencies and cancellation
- 10.3 · async/await, tasks, task groups, cancellation and task locals
- 10.4 · Actors, reentrancy, isolated, nonisolated, global actors and @MainActor
- 10.5 · Region-based isolation, sending, and migrating to Swift 6
- 10.6 · Continuations and bridging GCD, Combine and callback APIs
- 10.7 · Deadlocks, main-actor hops, Thread Sanitizer and Instruments
- 10.9 · Isolation rules, isolated parameters, global actors, main-actor hops and default isolation
- 10.10 · Sendable rules, locks versus actors, and the escape hatches
- 10.11 · Groups, semaphores, parallel loops, operation dependencies, QoS and timers
- 10.12 · AsyncStream buffering, continuation misuse and notifications as async sequences