tezvyn:

How task cancellation works with async/await

AI-drafted, machine-checkedSource: interviewadvanced
WHAT IT TESTS

Cooperative cancellation in Swift Concurrency.

OUTLINE

Cancellation is a flag, not a kill; check Task.isCancelled or call checkCancellation, URLSession throws CancellationError automatically.

WHAT THIS TESTS The interviewer wants to confirm you grasp that Swift Concurrency uses cooperative cancellation. A cancelled task is not killed; it is asked to stop, and well-written code honors that request at safe points.

A GOOD ANSWER COVERS Calling cancel() on a Task sets its isCancelled flag and propagates to child tasks in the structured tree. The task keeps running until it next checks. Suspension points provided by the system, including URLSession's data(from:) and data(for:), Task.sleep, and async sequences, detect cancellation and throw CancellationError automatically. So if you await such a call and the task is cancelled, the error surfaces and you can clean up with defer or catch. For your own CPU-bound or chunked work, you poll Task.isCancelled in a loop or call try Task.checkCancellation() at boundaries, then release resources and return or throw.

COMMON WRONG ANSWERS Claiming cancel() immediately tears the task down, or that it can interrupt a synchronous blocking call. Forgetting that withTaskCancellationHandler exists for resources that need active teardown, like closing a stream. Assuming a detached task inherits cancellation from its parent, which it does not.

LIKELY FOLLOW-UPS How to react the instant cancellation happens for a non-async resource: use withTaskCancellationHandler to run a closure when cancelled. Whether cancellation propagates across a TaskGroup: yes, cancelling the group cancels children. How SwiftUI .task ties cancellation to view lifetime: the task is cancelled when the view disappears.

ONE CONCRETE EXAMPLE A search screen kicks off a network call in .task as the user types. When they navigate away or the query changes, SwiftUI cancels the prior task. Because you await URLSession.data, that call throws CancellationError, you skip updating state, and the in-flight request is torn down so it does not waste bandwidth or overwrite fresh results. For a local file parse you would add try Task.checkCancellation() inside the read loop to stop promptly.

Read the original → developer.apple.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.