skip to content

Tasks, Groups and Cancellation

Tasks form a tree in which children finish before parents and cancellation is cooperative. Interviewers ask when to use a task group, why Task.detached is rare and how cancellation spreads.

on this pageshow

explore

questions

5

In Swift, how does `Task { }` start async work from a synchronous button action, and what does the returned handle let you do?

level: juniorimportance: must knowfreq 75%

answer

  1. unstructured, starts right away
  2. handle is yours to keep or drop
  3. value, result, cancel()
  4. errors wait for someone to await
  5. 6.4 warns on an unused throwing Task

basics

~20 s

Task { } creates an unstructured task that starts at once and returns a Task<Success, Failure> handle. Keep the handle to await value or result or to call cancel(); dropping it neither cancels the task nor surfaces its errors.

solid answer

~50 s

A synchronous function such as a button action cannot `await`, so it wraps the async call in `Task { ... }`. The new task is scheduled immediately and runs to completion whether or not anyone keeps the returned `Task<Success, Failure>` handle: releasing the handle does not cancel the task, it only removes your way to cancel it. Through the handle you can `try await task.value` (no `try` when `Failure` is `Never`), `await task.result` to get a `Result`, or call `task.cancel()`, which marks the task cancelled and relies on its code to stop. An error thrown inside the closure is kept by the task and rethrown only when someone awaits `value`, so a fire-and-forget throwing task loses it silently; Swift 6.4 adds a warning for exactly that case. Handle the error inside the closure, or store the handle and read its result.

code

swift · 31 lines
swift
@MainActor
final class PhotoUploadScreen {
    private var uploadTask: Task<Int, any Error>?

    func uploadTapped(names: [String]) {
        uploadTask = Task {
            var sent = 0
            for name in names {
                try await send(name)
                sent += 1
            }
            return sent
        }
    }

    func screenClosed() {
        uploadTask?.cancel()
    }

    func summary() async -> String {
        guard let uploadTask else { return "nothing started" }
        switch await uploadTask.result {
        case .success(let count): return "sent \(count)"
        case .failure(let error): return "stopped: \(error)"
        }
    }
}

func send(_ name: String) async throws {
    try await Task.sleep(for: .milliseconds(100))
}

go deeper

for a junior

Recall that Task { } is how synchronous code starts async work, that it runs at once, and that the handle gives you value, result and cancel().

for a middle

Explain why the handle's lifetime does not control the task's lifetime, where a thrown error goes, and why value needs try while result does not.

for a senior

Show how you would store and cancel handles per screen, avoid duplicate tasks on repeated taps, and make sure no thrown error is silently dropped.

for a principal

Weigh a team rule against bare fire-and-forget throwing tasks, now backed by the 6.4 warning group, against the noise it adds to legacy code.

## Why a synchronous function needs `Task { }` An `async` function can only be called with `await`, and `await` is only legal inside an asynchronous context. A button action, a delegate callback or a lifecycle method is **synchronous**, so it cannot call `upload(photo)` directly. `Task { ... }` is the bridge: it creates a new **unstructured task**, an asynchronous context of its own, and returns at once so the synchronous caller can carry on. - **Unstructured** means the task has no parent task. Nothing waits for it at the end of the caller's scope, and cancelling the code that created it does not cancel it. - The task is **scheduled immediately**. You do not need to keep or await anything for it to run. - The initializer is `Task.init(name:priority:operation:)`; `name` and `priority` are optional, so the common call site is just a trailing closure. ## What the handle is `Task { }` returns a value of type `Task<Success, Failure>`. `Success` is whatever the closure returns, often `Void`, and `Failure` is `Never` for a closure that cannot throw or `any Error` for one that can. The handle is a small reference to the running task, not the task's work itself. | Member | What it gives you | |---|---| | `value` | The closure's return value, awaited; `try await` when `Failure` is not `Never`, because the stored error is rethrown here | | `result` | A `Result<Success, Failure>`, awaited without `try` | | `cancel()` | Marks the task cancelled; the task's own code must notice and stop | | `isCancelled` | Whether this task has been cancelled, readable from outside the task | The standard library's documentation states the lifetime rule plainly: discarding your reference to a task does not implicitly cancel it; it only makes it impossible for you to cancel it explicitly. So `Task { await refresh() }` with the result thrown away is a legitimate fire-and-forget call, while a screen that must stop its work on exit has to **store the handle** in a property. ## Errors inside an unstructured task When the closure throws, the error does not travel anywhere on its own. The task catches it and holds it until someone awaits `value` (which rethrows it) or `result` (which returns `.failure`). If nobody ever does, the error is simply gone. That is why this line looks harmless and is not: ```swift Task { try await upload("IMG_0001.jpg") } // error is silently dropped ``` Swift 6.4 (SE-0520) gives the throwing Task initializers typed throws and adds a warning in the `NoUseUnstructuredThrowingTask` group when such a task's handle is not used: "unstructured throwing task created by 'init(name:priority:operation:)' is not used, which may accidentally ignore errors thrown inside the task". A non-throwing `Task { }` gets no warning. The fixes are the two the compiler's note suggests: 1. Handle the error **inside** the closure with `do`/`catch`, so `Failure` becomes `Never`. 2. **Store** the handle (or assign it to `_` deliberately) and read `value` or `result` somewhere. ## Keeping the handle: the photo uploader In the photo uploader, tapping Upload starts sending 50 images and leaving the screen must stop them. The screen object keeps a `Task<Int, any Error>?` property: the action assigns the new task to it, the close handler calls `uploadTask?.cancel()`, and a summary method awaits `uploadTask.result` to report either the number sent or the error. Because `Task.sleep(for:)` and many library async calls throw `CancellationError` when their task is cancelled, the run ends with `.failure(CancellationError())` instead of finishing all 50. If the screen object is main-actor isolated, the task's closure runs on the main actor too, so it may read and write the screen's properties without `await`; which isolation a task inherits, and what `Task.detached` drops, is a question of its own. How the closure should capture `self` is the material on capture lists. ## Mistakes that show up in review - Expecting a task to stop when its handle is released, the way some reactive subscriptions do when their token is deallocated. - Calling `cancel()` and assuming the work halted; it only sets a flag that code inside the task checks. - Writing `Task { try ... }` in an action with no `do`/`catch` and no stored handle, so failures never reach the user. - Starting a new `Task` on every tap without cancelling the previous one, so two uploads race. - Awaiting `value` on a throwing task without `try`; the compiler rejects it because `value` rethrows the stored error.

  • How do you deliberately fire and forget a throwing task in Swift 6.4 without the warning?
    Either catch inside the closure so the task's `Failure` is `Never`, or make the discard explicit with `_ = Task { try await upload(name) }`, which the compiler's note accepts as storing or discarding the task value. The first is usually better: an explicit discard still loses the error, it just says so on purpose.
  • What is the difference between `task.value` and `task.result` on a throwing `Task`?
    `value` rethrows the stored error, so it needs `try await` and a `do`/`catch` or a throwing caller. `result` never throws; it returns `Result<Success, Failure>` and you switch over `.success` and `.failure`. Both suspend until the task finishes, and both can be awaited more than once.
  • Does awaiting a task's `value` from a cancelled caller cancel the awaited task?
    No. An unstructured task is not a child of whoever awaits it, so the caller's cancellation does not reach it. If the waiting code should cancel the work when it is itself cancelled, it has to call `cancel()` on the handle, for example from a cancellation handler.

  • Releasing the Task handle cancels the task automatically.
  • An error thrown inside Task { } crashes the app or reaches the caller.
  • cancel() stops the task's work immediately at any instruction.
  • You must await every Task you create or it never runs.
  • Task { } blocks the button action until the async work completes.

Assumes Swift 6.4, which added the NoUseUnstructuredThrowingTask warning for an unused throwing Task (SE-0520); earlier releases accept the same code silently.

open as a page

In Swift, what does calling `cancel()` on a `Task` actually do, and how should the task's own code notice and respond?

level: middleimportance: must knowfreq 72%

basics

~20 s

Calling 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.

open as a page

In Swift, what does a `Task { }` created inside a `@MainActor` method inherit, and why is `Task.detached` rarely the right tool?

level: middleimportance: must knowfreq 70%

basics

~20 s

Task { } inherits the creator's actor isolation, base priority and task-local values, but not its cancellation. Task.detached inherits none of these, so it is rarely right: you lose context and must hop back to the main actor yourself.

open as a page

In Swift, how does a `@TaskLocal` value carry a request ID into every log line of an upload, and which tasks can read it?

level: middleimportance: should knowfreq 30%

basics

~20 s

Declare @TaskLocal static var requestID: String?, bind it with $requestID.withValue(id) { ... }, and code in that scope reads it like a static property. Child tasks and Task { } inherit the binding; Task.detached reads the default.

open as a page

In Swift, how would you upload 50 photos with `withThrowingTaskGroup` keeping at most four in flight, and what happens when one upload throws?

level: seniorimportance: should knowfreq 50%

basics

~20 s

A Swift task group has no width limit: add four uploads, then one more each time next() returns. A child's error surfaces at next(); letting it escape cancels the other children, which the group awaits before rethrowing.

open as a page