Skip to content
Tutorials Center
My learning

Topics

Lesson 86 of 146 ยท Concurrency

Cancellation and Timeouts

Learn cooperative cancellation in Swift concurrency - Task.cancel, isCancelled, checkCancellation, CancellationError, propagation to child tasks, cleanup, cancellation handlers and a timeout helper.

Starting work is easy. Stopping it is the hard part. A user taps "back" while a download is running. A search box fires a new query before the old one has finished. A request has been waiting for ten seconds and you want to give up. In each case, work that is already running has become pointless, and a good program stops it quickly instead of wasting time, battery and network.

Swift calls this cancellation, and the most important thing to know is in its design: cancellation is cooperative. Nobody kills a task from outside. Cancelling only asks the task to stop, and the task has to notice the request and finish gracefully. This lesson shows how to ask, how to notice, how cancellation travels through child tasks, how to clean up, and how to build a timeout. It follows Tasks, Task groups and AsyncSequence and AsyncStream.

Asking a task to stop

Every task has a cancelled flag. Calling cancel() on a task handle sets that flag. Nothing else happens: no code is interrupted and no error is thrown by itself. Code inside the task can read the flag with Task.isCancelled.

Swift Task.cancel and Task.isCancelled

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The output is noticed the request, isCancelled = true, then did some work: true, then handle says cancelled: true. The loop keeps going until it sees the flag. If the loop never looked at the flag, it would never stop: cancellation can only be noticed by code that checks.

The flag only ever goes from false to true. A cancelled task stays cancelled, even after it has handled the request. You also cannot "un-cancel" a task. Start a new one instead.

Code that ignores cancellation

To make this concrete, here is a task that does three steps and never checks the flag. We cancel it before it even starts working:

Swift Cancellation is only a request

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

All three steps run, and the last line says isCancelled = true. The task was told to stop, ignored the request, and completed anyway. Every long-running piece of your own code that you want to be cancellable needs a check.

Throwing on cancellation

Checking the flag and returning early works, but a task often wants to throw and let the error unwind everything. Two tools do that:

  • try Task.checkCancellation() throws CancellationError if the current task is cancelled, and does nothing otherwise.
  • Many standard async functions, Task.sleep first among them, check for you and throw CancellationError when cancelled.
Swift Task.sleep throws CancellationError

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The program prints caught: CancellationError() and then finished without waiting 10 seconds. A cancelled task that is already sleeping wakes up at once, and a task that starts a sleep after it was cancelled throws immediately.

For your own loops, put a check at the top of each iteration or at other safe points:

Swift Task.checkCancellation in a loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

You get first task failed: CancellationError() and second task: 6. The check is cheap, so it is fine to run it often. For tight loops with very small iterations, check every few hundred rounds instead.

Choosing between isCancelled and checkCancellation

You want to Use
Stop and return a partial result if Task.isCancelled { break } or return partial
Stop and report it as an error try Task.checkCancellation()
Wait for something and stop waiting An async call that throws on cancel, such as Task.sleep

Returning a partial result is sometimes right (a search that shows what it has so far). Throwing is right when the result would be wrong or incomplete if used.

try? hides cancellation. A line such as try? await Task.sleep(for: .milliseconds(5)) swallows the CancellationError, so the surrounding loop carries on. This loop prints three ticks even though the task was cancelled first:

Swift try? swallows the cancellation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

All of tick 1, tick 2 and tick 3 appear. This is fine in this site's short examples, where we only wanted a delay, but in real code write try await and let the error propagate, or check Task.isCancelled yourself.

Cancellation travels downwards

Cancelling a task cancels its children too, but only the structured ones. The rule:

  • Structured children (async let and task group tasks) are cancelled automatically when their parent is.
  • Unstructured tasks (Task { } and Task.detached { }) are not. They are independent, so you must cancel them yourself.

First, structured children. Two async let values wait for five seconds each. We cancel the parent after a short time:

Swift Cancelling a parent cancels async let children

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The result is parent ended with: CancellationError() and then ["cleanup a", "cleanup b"]. Both children woke up immediately, ran their defer blocks, and the whole thing took a fraction of a second instead of five. I used an actor and sorted() for the log because the order in which the two children clean up is not guaranteed.

Now unstructured tasks:

Swift Unstructured tasks are not cancelled with their parent

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Both print false. The outer task was cancelled, but the Task { } and Task.detached created inside it carry on as if nothing happened. This is a classic source of leaks, and it is why structured concurrency (task groups and async let) is preferred: cancellation, errors and waiting all work for free. When you do need an unstructured task, keep its handle and cancel it yourself, for example in the owner's cleanup method.

Cleaning up when cancelled

When a task is cancelled it should release resources promptly. The tool is the one you already know: defer (see defer and Cleanup), which runs no matter how the scope exits. A catch for CancellationError is the right place to do cleanup that must be async:

Swift Cleanup before rethrowing CancellationError

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The output is cancelled; cleaning up, cleanup done, outcome: CancellationError(). Note the last throw: if you catch the cancellation and then continue as if it were a normal result, callers cannot tell that the work was abandoned. Rethrow it, or return a clearly "cancelled" value.

A word of warning about cleanup that awaits: a cancelled task's later await calls (such as Task.sleep) can throw straight away, because the flag stays set. Cleanup code that must not be interrupted should use APIs that do not check cancellation, or be run in a separate unstructured Task that is not cancelled.

Reacting immediately: cancellation handlers

Sometimes you need to do something the instant cancellation happens, not at the next check. Think of closing a network request or telling a device to stop. withTaskCancellationHandler runs your onCancel closure as soon as the task is cancelled, from whichever thread called cancel():

Swift withTaskCancellationHandler

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

You see onCancel ran, operation ended with: CancellationError() and operation returned. The handler fires immediately, while the operation notices at its next suspension. The onCancel closure must be @Sendable and quick, because it can run concurrently with the operation, so it may not touch non-Sendable state (Sendable). It is mostly used when wrapping old APIs that have their own cancel() method, which is the topic of Bridging Callbacks to async.

Cancellation in task groups and streams

A task group cancels its children in these cases: you call group.cancelAll(), the group's body throws, or the task that owns the group is cancelled. You saw cancelAll() in Task groups. A for await loop over an AsyncStream ends when its task is cancelled, and the stream's onTermination callback receives .cancelled.

Building a timeout

Swift's standard library has no withTimeout, but one is easy to write with a throwing task group: race the real work against a sleeping task that throws a timeout error. Whoever finishes first wins, and cancelAll() stops the loser.

Swift A timeout helper built from a task group

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first call succeeds and prints fetched after 10 ms. The second is far slower than its limit: the timer child throws TimeoutError first, cancelAll() makes the sleeping fetch throw CancellationError, and the program prints timed out. Note the order: the first element from group.next() decides the outcome, either the value or the error.

There is an important limit. A task group does not return until all of its children have finished, and cancellation is cooperative. So a timeout only returns quickly if the operation cooperates. See what happens with an operation that swallows cancellation:

Swift A timeout cannot stop code that ignores cancellation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The output is stubborn finished its work, caught: TimeoutError(), after. The error was decided after 30 ms, but withTimeout could only return once the stubborn child ended, about 200 ms later. The lesson: a timeout is only as good as the cancellation support of the code it wraps. Make your operations check for cancellation, and avoid try? on sleeps and network calls.

Never print or compare exact timings in tests of timeout code. Make the slow operation much slower than the limit (seconds against milliseconds) and assert on the outcome, not on how long it took.

Design guidelines

  • Make long work cancellable. Check Task.isCancelled or call try Task.checkCancellation() in loops, and prefer APIs that throw on cancellation.
  • Do not swallow CancellationError. Avoid try? on awaits, and rethrow after cleanup.
  • Prefer structured concurrency (async let, task groups) so cancellation propagates by itself.
  • Keep handles of unstructured tasks that you may need to cancel, and cancel the old one before starting a new one (the "search as you type" pattern).
  • Clean up with defer so resources are released on cancel, error and success alike.
  • Treat cancellation as a normal outcome, not a failure to report to the user.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does calling task.cancel() do?

    Cancellation is cooperative. cancel() only sets a flag, and the task must check it or call something that throws when cancelled.
  2. 2. Which line makes a loop stop with an error when the task is cancelled?

    try Task.checkCancellation() throws CancellationError. isCancelled only reads the flag, and try? would swallow the error.
  3. 3. A parent task is cancelled. Which of its children are cancelled automatically?

    Structured children (async let and task group tasks) inherit cancellation. Unstructured Task { } and detached tasks are independent and must be cancelled by hand.
  4. 4. Why can try? await Task.sleep(...) inside a loop be a bug?

    try? turns the thrown CancellationError into nil, and the code continues as if nothing happened.
  5. 5. A timeout helper races the operation against a sleeping task in a task group. The operation ignores cancellation. What happens when the timer fires?

    cancelAll() only requests cancellation. Since the group waits for every child, the timeout error is delayed until the stubborn operation ends.

Summary

  • Cancellation is cooperative: task.cancel() sets a flag, and the task must notice it.
  • Read the flag with Task.isCancelled, or throw CancellationError with try Task.checkCancellation(); Task.sleep and many other async calls throw it for you.
  • async let and task group children are cancelled with their parent; Task { } and Task.detached are not, so keep their handles.
  • Do not hide cancellation with try?; clean up with defer or a catch is CancellationError block, and rethrow afterwards.
  • withTaskCancellationHandler runs code immediately when cancellation happens, which helps when wrapping APIs that have their own cancel method.
  • A timeout is a race between the work and a sleeping task in a throwing task group, and it only returns quickly if the work cooperates.

Next: Bridging Callbacks to async shows how to wrap older callback-based APIs so they work with await.