In Swift, what does calling `cancel()` on a `Task` actually do, and how should the task's own code notice and respond?
answer
- a flag, not a kill
- children see it, unstructured tasks do not
- isCancelled vs checkCancellation()
- a handler for blocking work
- 6.4 shields protect cleanup
basics
~20 sCalling cancel() on a Swift Task only sets its cancelled flag, which also reaches its child tasks; nothing stops by force. The code must check Task.isCancelled or call Task.checkCancellation(), then stop by throwing CancellationError or returning partial results.
solid answer
~40 sSwift cancellation is **cooperative**. `cancel()` marks the task cancelled, permanently, and propagates the mark to its child tasks in task groups and `async let`, but not to unstructured tasks it created. Running code keeps running until it looks: `Task.checkCancellation()` throws `CancellationError`, and the static `Task.isCancelled` returns a Bool so you can clean up and return what you have. Many library calls check for you; `Task.sleep(for:)` throws `CancellationError` once its task is cancelled. For work that cannot poll, such as a blocking call or a callback-based connection, `withTaskCancellationHandler(operation:onCancel:)` runs the handler as soon as cancellation arrives, possibly concurrently with the operation. Swift 6.4 adds `withTaskCancellationShield`, so cleanup that checks for cancellation still runs to completion in a cancelled task.
code
swift · 30 linesfinal class UploadConnection: Sendable {
func close() { print("connection closed") }
}
func flushLog() async {
guard !Task.isCancelled else { print("flush skipped"); return }
print("log flushed")
}
func uploadAll() async throws {
let connection = UploadConnection()
defer {
await withTaskCancellationShield { await flushLog() }
}
try await withTaskCancellationHandler {
try await Task.sleep(for: .seconds(10))
} onCancel: {
connection.close()
}
}
@main
struct Demo {
static func main() async {
let job = Task { try await uploadAll() }
try? await Task.sleep(for: .milliseconds(50))
job.cancel()
print(await job.result)
}
}go deeper
Recall that cancel() only asks the task to stop, and that Task.checkCancellation() or Task.isCancelled is how the task finds out.
Explain which tasks a cancellation reaches, when to throw versus return partial results, and what withTaskCancellationHandler adds over polling.
Show how you make blocking or callback-driven work cancellable, avoid try? swallowing CancellationError, and keep cleanup running in a cancelled task.
Set the team's expectations for cancellation checks in long-running work, and decide when 6.4 shields are worth requiring for cleanup paths.
## Cancellation is a flag In Swift, cancelling a task never interrupts it. `task.cancel()` sets a **cancelled flag** on the task. The documentation for `isCancelled` says it plainly: once the value becomes `true` it stays `true`, and there is no way to uncancel a task. What the flag reaches: - **The task itself**, whose code can now observe it. - **Its child tasks**: children in a task group and `async let` children are cancelled with their parent, recursively. - **Not unstructured tasks** it created with `Task { }` or `Task.detached`; they have no parent and need their own `cancel()`. Cancelling a task group's parent, or calling `group.cancelAll()`, cancels every child in that group, and a child added to a cancelled group starts out cancelled. ## How code notices The Swift book names two ways to check, and both read the current task's state: | API | Behaviour when cancelled | Use it when | |---|---|---| | `Task.checkCancellation()` | Throws `CancellationError` | The function already throws and stopping is all you need | | `Task.isCancelled` (static) | Returns `true` | You want to clean up, return partial results or `nil` | | `task.isCancelled` (on a handle) | Returns `true` | Code outside the task wants to know its state | Responding is your choice. The book lists three usual answers: throw an error such as `CancellationError`, return `nil` or an empty collection, or return the work completed so far. In the photo uploader, a loop that checks before each photo stops between photos; the photo in flight finishes or fails on its own terms. Library code often checks for you. `Task.sleep(for:)` throws `CancellationError` when its task is cancelled, and many system async APIs end early with a cancellation error. Synchronous code never does: a CPU-bound loop that neither checks nor awaits runs to the end after `cancel()`. For such loops, check every iteration or every batch of items; how often the loop checks bounds how long a cancelled task keeps working. ## `withTaskCancellationHandler` Polling does not help when the work sits inside something that does not return until it is done, such as a blocking call or a connection driven by callbacks. `withTaskCancellationHandler(operation:onCancel:)` registers a handler that runs **immediately** when the task is cancelled: 1. The `operation` closure always runs, on the caller's context. 2. If the task is already cancelled when the call starts, the handler runs right away, before `operation`. 3. If cancellation arrives later, the handler runs at most once, **concurrently** with `operation`. 4. The handler is synchronous and must be safe to run concurrently. The documentation warns that it may run while internal task locks are held, so if the handler takes a lock, other code should not cancel tasks or resume continuations while holding that lock. The handler does not stop `operation` either. Its job is to poke the underlying work, for example by closing the connection, so that `operation` returns or throws promptly. Cancellation is still cooperative. ## Cleanup in a cancelled task: shields (Swift 6.4) A cancelled task still has to release what it holds. The trap is that cleanup code may itself check for cancellation and skip its work. Swift 6.4 (SE-0504) adds `withTaskCancellationShield { }`: - Inside the shield, the static `Task.isCancelled` returns `false`, `Task.checkCancellation()` does not throw, and cancellation handlers do not fire. - Child tasks created inside the shield do not inherit the cancellation. - The shield does not undo anything. When the scope ends, the task's real cancelled state is visible again, and the instance property `task.isCancelled` reports the real state even inside the shield. Swift 6.4 also allows `await` inside `defer` (SE-0493), so `defer { await withTaskCancellationShield { await flushLog() } }` runs an async cleanup to completion on the way out of a cancelled upload. The rules of `defer` itself are covered with early exits and `defer`. ## Mistakes that show up in review - Calling `cancel()` on a handle and updating the UI as if the work had stopped. - Checking once at the top of a long function, so every step after the check runs even when cancellation arrives halfway through. - A long synchronous loop with no checks, then surprise that cancellation is ignored. - Catching every error with `try?` around `Task.sleep`, which swallows `CancellationError` and keeps looping. - Sharing mutable state between an `onCancel` handler and the operation without synchronization.
- Why can `try? await Task.sleep(for:)` inside a polling loop keep the loop running after cancellation?Because `try?` turns the `CancellationError` that `Task.sleep` throws into `nil`, and the loop carries on to the next iteration. Either let the error propagate with `try`, or check `Task.isCancelled` in the loop condition so the loop exits once the task is cancelled.
- When should code read `task.isCancelled` on a handle instead of the static `Task.isCancelled`?Mainly from outside the task, to ask about that particular task. Inside the task, the static property is the one to use: it reads the current task and respects an active cancellation shield, while the instance property always reports the real state.
- Does `withTaskCancellationHandler` make a blocking synchronous call return early?Only if the handler can make it return. The handler runs concurrently with the operation, so it can close a connection or set a flag the blocking code watches, but the operation itself is never interrupted. If nothing it can reach unblocks the call, the call runs to completion.
- cancel() interrupts the task at its next instruction.
- Cancelling a task also cancels the Task { } instances it created.
- A cancelled task can be uncancelled by catching CancellationError.
- The onCancel handler waits until the operation reaches its next await.
- Synchronous loops are stopped by the runtime when their task is cancelled.
Assumes Swift 6.4, which added task cancellation shields (SE-0504) and async calls in defer (SE-0493); isCancelled, checkCancellation() and withTaskCancellationHandler date from Swift 5.5.