Tasks and cancellation
suggest changeEvery piece of async code in Swift runs inside a task. A task is a unit of asynchronous work that has a priority, can be cancelled, and can carry task-local values. Swift 5.5 introduced tasks together with async/await (see async and await).
There are two kinds of tasks:
- Structured (child) tasks are created with
async letand task groups. They belong to the scope that created them, which waits for them to finish and cancels them when it exits early. See Structured concurrency with async let and TaskGroup. - Unstructured tasks are created with
Task { }andTask.detached { }. They aren't tied to a scope. You get back aTaskhandle that you can await or cancel, and you are responsible for the task's lifetime.
This article is about unstructured tasks, and about cancellation, which works the same way for both kinds.
Task { } |
Task.detached { } |
async let / task group |
|
|---|---|---|---|
| Kind | unstructured | unstructured | structured (child) |
| Inherits priority | yes | no | yes |
| Inherits task-local values | yes | no | yes |
| Inherits actor isolation | yes | no | no |
| Cancelled when parent is cancelled | no | no | yes |
| Must be awaited | no | no | yes, before the scope exits |
The examples were compiled with Swift 6.4 on Windows, in the Swift 6 language mode:
swiftc -swift-version 6 -parse-as-library main.swift
Task.immediate and task names need Swift 6.2 or later. Everything else works with Swift 5.5 and later, except Task.sleep(for:), which needs Swift 5.7.
Creating a task and waiting for its value
Task { ... } starts running the closure right away, concurrently with the code that created it. The returned handle has the type Task<Success, Failure>. Await task.value to get the result:
func download(_ name: String) async -> Int {
try? await Task.sleep(for: .milliseconds(100))
return name.count * 100
}
enum FetchError: Error { case notFound }
@main
struct Main {
static func main() async {
let task = Task {
await download("report.pdf")
}
print("task started, doing other work")
let size = await task.value
print("downloaded \(size) bytes")
print(type(of: task))
let failing = Task {
try await Task.sleep(for: .milliseconds(10))
throw FetchError.notFound
}
do {
_ = try await failing.value
} catch {
print("task failed: \(error)")
}
print(await failing.result)
}
}
Output:
task started, doing other work
downloaded 1000 bytes
Task<Int, Never>
task failed: notFound
failure(main.FetchError.notFound)
Things to know:
- If the closure can't throw, the type is
Task<T, Never>andawait task.valuedoesn't needtry. If it can throw, the type isTask<T, any Error>and you needtry await task.value. task.resultgives you aResult<Success, Failure>instead of throwing.- You can await
valueany number of times, from any number of places. The task runs only once, and every caller gets the same result. - The
Taskinitializer is marked@discardableResult.Task { ... }on its own line starts a fire-and-forget task. That's common in UI event handlers, but then nobody can wait for the task or cancel it. - Dropping the handle does not cancel the task. It keeps running until it finishes.
Starting a Task is also how synchronous code (a callback, a button handler) calls async code.
Task vs Task.detached
Task { } inherits three things from the context where it is created:
- The actor isolation. Inside an actor method or a
@MainActorfunction, the task runs on that actor too. - The priority of the current task.
- The task-local values (see below).
Task.detached { } inherits none of them. It runs on the global concurrent executor, as if it had been created from nowhere.
actor Counter {
var value = 0
func incrementLater() -> Task<Void, Never> {
// inherits the actor's isolation: may touch `value` directly
Task {
value += 1
print("Task: value = \(value)")
}
}
func incrementDetached() -> Task<Void, Never> {
// runs outside the actor: must await to get back in
Task.detached {
await self.bump()
print("detached: value = \(await self.value)")
}
}
func bump() { value += 1 }
}
@main
struct Main {
static func main() async {
let counter = Counter()
await counter.incrementLater().value
await counter.incrementDetached().value
}
}
Output:
Task: value = 1
detached: value = 2
In incrementDetached, writing value += 1 directly would not compile: "actor-isolated property 'value' can not be mutated from a nonisolated context".
Inside an actor, the task's closure captures self strongly, without an explicit self.. The actor stays alive until the task finishes. That's usually what you want for short tasks. For a long-running loop, keep the handle and cancel it (see the search example below).
Use Task { } by default. Task.detached is for the rare case where you explicitly don't want the current context. One example is CPU-heavy work started from the main actor that should not run on the main actor. Even then, a nonisolated or @concurrent (Swift 6.2) async function called from a plain Task is often clearer.
Priorities
You can give a task a priority with Task(priority:). The values are .high, .medium, .low and .background, plus .userInitiated (the same as .high) and .utility (the same as .low). Task.currentPriority reads the priority of the current task:
@main
struct Main {
static func main() async {
let outer = Task(priority: .high) {
print("outer: \(Task.currentPriority)")
let inner = Task { print("Task: \(Task.currentPriority)") }
let detached = Task.detached { print("detached: \(Task.currentPriority)") }
await inner.value
await detached.value
}
await outer.value
print("main: \(Task.currentPriority)")
}
}
Output:
outer: TaskPriority.high
Task: TaskPriority.high
detached: TaskPriority.medium
main: TaskPriority.medium
Task { } copied the .high priority from its parent. Task.detached got the default (.medium).
Priority is a hint to the scheduler, not a guarantee of ordering. The runtime also escalates priority. When a higher-priority task awaits a lower-priority one, the awaited task temporarily runs at the higher priority, so it isn't starved. Task.basePriority stays the same:
@main
struct Main {
static func main() async {
let bg = Task(priority: .background) {
print("start: current \(Task.currentPriority), base \(Task.basePriority!)")
try? await Task.sleep(for: .milliseconds(200))
print("resumed: current \(Task.currentPriority), base \(Task.basePriority!)")
}
try? await Task.sleep(for: .milliseconds(100))
await bg.value // main runs at .medium, so bg is escalated
}
}
Output:
start: current TaskPriority.background, base TaskPriority.background
resumed: current TaskPriority.medium, base TaskPriority.background
Cancellation is cooperative
task.cancel() doesn't stop a task. It only sets a flag. The code running in the task must check the flag and decide what to do: return early, return a partial result, or throw. If it never checks, cancellation has no effect.
Check the flag with Task.isCancelled, a static property that refers to the current task:
func sumOfSquares(upTo n: Int) async -> Int {
var total = 0
for i in 1...n {
if Task.isCancelled {
print("cancelled at i = \(i)")
return total // return what we have so far
}
total += i * i
if i % 1000 == 0 { await Task.yield() }
}
return total
}
@main
struct Main {
static func main() async {
let ignores = Task {
// never checks the flag: cancel() changes nothing
var x = 0
for i in 0..<5 { x += i }
return x
}
ignores.cancel()
print("ignores:", await ignores.value)
let task = Task { await sumOfSquares(upTo: 100_000_000) }
try? await Task.sleep(for: .milliseconds(20))
task.cancel()
print("isCancelled:", task.isCancelled)
let partial = await task.value
print("partial result > 0:", partial > 0)
}
}
Output (the value of i differs from run to run):
ignores: 10
isCancelled: true
cancelled at i = 700001
partial result > 0: true
task.isCancelled (on the handle) and Task.isCancelled (inside the task) read the same flag. Once a task is cancelled it stays cancelled. There is no way to undo it.
Task.yield() suspends briefly so other tasks can run. A long CPU-bound loop in a task should yield now and then. Otherwise it occupies a thread of the cooperative pool for its whole run.
Compare this with Operation (see Running Tasks in an OperationQueue). There, too, cancel() only sets isCancelled and the operation's main() has to check it. The difference is that Swift tasks propagate the flag to child tasks automatically, and the async APIs in the standard library check it for you.
checkCancellation and CancellationError
In a throwing function, the usual reaction to cancellation is to throw CancellationError. try Task.checkCancellation() does exactly that: it throws if the task is cancelled and does nothing otherwise. Many async APIs, including Task.sleep, check by themselves and throw CancellationError too:
func processFiles(_ files: [String]) async throws -> [String] {
var done: [String] = []
for file in files {
try Task.checkCancellation() // throws CancellationError
print("processing \(file)")
try await Task.sleep(for: .milliseconds(100)) // also throws when cancelled
done.append(file)
}
return done
}
@main
struct Main {
static func main() async {
let files = ["a.txt", "b.txt", "c.txt", "d.txt", "e.txt"]
let task = Task { try await processFiles(files) }
try? await Task.sleep(for: .milliseconds(150))
task.cancel()
do {
let done = try await task.value
print("finished: \(done)")
} catch is CancellationError {
print("stopped: CancellationError")
} catch {
print("other error: \(error)")
}
// a task cancelled before it runs sees the flag right away
let early = Task {
print("isCancelled at start:", Task.isCancelled)
try await Task.sleep(for: .seconds(10))
print("never printed")
}
early.cancel()
print(await early.result)
}
}
Output:
processing a.txt
processing b.txt
stopped: CancellationError
isCancelled at start: true
failure(Swift.CancellationError())
The task was cancelled while it slept on b.txt, so Task.sleep threw right away. The second task never waited its 10 seconds.
Where should you check? At the start of each unit of work: each loop iteration, each file, each page of results. Before expensive steps, too. Checking at every line isn't needed, because most await calls on system APIs already check.
Be careful with try?. try? await Task.sleep(...) swallows the CancellationError, and the code continues as if nothing happened. In real code, use try await or check Task.isCancelled after the sleep.
Reacting immediately: withTaskCancellationHandler
Polling the flag isn't enough when a task is blocked waiting on something that doesn't know about Swift tasks: a callback-based API, a socket, a child process. withTaskCancellationHandler runs an onCancel closure immediately when the task is cancelled. In that closure you tell the underlying operation to stop.
Here an old-style download object with its own cancel() method is wrapped in an async function. (withCheckedThrowingContinuation turns the callback into an await; see async and await.)
import Foundation
import Synchronization
// An old-style API: works on a background thread,
// can be stopped with cancel(), reports through a callback.
final class LegacyDownload: Sendable {
private let cancelled = Atomic<Bool>(false)
func start(completion: @escaping @Sendable (Result<String, Error>) -> Void) {
DispatchQueue.global().async {
for _ in 0..<20 {
if self.cancelled.load(ordering: .relaxed) {
completion(.failure(CancellationError()))
return
}
Thread.sleep(forTimeInterval: 0.05)
}
completion(.success("file contents"))
}
}
func cancel() {
print("LegacyDownload.cancel() called")
cancelled.store(true, ordering: .relaxed)
}
}
func download() async throws -> String {
let job = LegacyDownload()
return try await withTaskCancellationHandler {
try await withCheckedThrowingContinuation { continuation in
job.start { continuation.resume(with: $0) }
}
} onCancel: {
job.cancel() // runs as soon as the task is cancelled
}
}
@main
struct Main {
static func main() async {
let task = Task { try await download() }
try? await Task.sleep(for: .milliseconds(200))
let start = ContinuousClock.now
task.cancel()
print(await task.result)
print("stopped quickly:", ContinuousClock.now - start < .milliseconds(200))
print(try! await Task { try await download() }.value)
}
}
Output:
LegacyDownload.cancel() called
failure(Swift.CancellationError())
stopped quickly: true
file contents
Without the handler, the cancelled task would wait the full second for the download to finish, because nothing in it checks Task.isCancelled.
Rules for the onCancel closure:
- It runs concurrently with the operation, on whatever thread called
cancel(). It must be@Sendable, and anything it shares with the operation must be thread-safe. That's whyLegacyDownloaduses anAtomic(see the Synchronization module). - If the task is already cancelled when
withTaskCancellationHandleris called,onCancelruns right away, before the operation starts. The operation still runs, so it should check the flag too. - Keep it short and non-blocking. Signal the work to stop; don't wait for it there.
- The operation must still finish (here: resume the continuation). The handler only asks it to finish sooner.
Cancellation doesn't cross into unstructured tasks
Cancelling a task cancels its child tasks (async let and task groups). It does not cancel unstructured tasks created inside it, because they have no parent:
func work(_ label: String) async {
do {
try await Task.sleep(for: .milliseconds(300))
print("\(label): finished")
} catch {
print("\(label): cancelled")
}
}
@main
struct Main {
static func main() async {
let outer = Task {
async let child: Void = work("async let child")
let unstructured = Task { await work("inner Task {}") }
await child
await unstructured.value
}
try? await Task.sleep(for: .milliseconds(50))
outer.cancel()
await outer.value
// dropping the handle does not cancel the task either
_ = Task { await work("fire-and-forget") }
try? await Task.sleep(for: .milliseconds(400))
}
}
Output:
async let child: cancelled
inner Task {}: finished
fire-and-forget: finished
If an inner Task { } should stop together with its creator, keep its handle and cancel it yourself. You can do that in a withTaskCancellationHandler around the await. Usually it's simpler to use async let or a task group instead.
Example: cancel the previous search
A common use of an unstructured task is "search as you type". Each keystroke starts a new search and cancels the previous one, so only the latest query produces results. A short sleep at the start doubles as a debounce: if the user keeps typing, the task is cancelled before it does any real work.
func search(_ query: String) async throws -> [String] {
try await Task.sleep(for: .milliseconds(100)) // pretend network call
return ["\(query) result 1", "\(query) result 2"]
}
@MainActor
final class SearchModel {
private var searchTask: Task<Void, Never>?
var results: [String] = []
func queryChanged(_ query: String) {
searchTask?.cancel() // drop the previous search
searchTask = Task {
do {
try await Task.sleep(for: .milliseconds(150)) // debounce
let found = try await search(query)
results = found
print("showing results for \"\(query)\"")
} catch is CancellationError {
print("search for \"\(query)\" cancelled")
} catch {
print("search failed: \(error)")
}
}
}
func waitForSearch() async { await searchTask?.value }
isolated deinit {
searchTask?.cancel()
}
}
@main
struct Main {
static func main() async {
let model = SearchModel()
for query in ["s", "sw", "swi", "swift"] {
model.queryChanged(query)
try? await Task.sleep(for: .milliseconds(40)) // user typing
}
await model.waitForSearch()
print(model.results)
}
}
Output:
search for "s" cancelled
search for "sw" cancelled
search for "swi" cancelled
showing results for "swift"
["swift result 1", "swift result 2"]
queryChanged is a synchronous @MainActor method, which is what a UI callback looks like. The Task inherits the main actor, so it can assign results without await. The try await after the sleep matters: with try? a cancelled task would carry on and overwrite the results with stale data.
isolated deinit (Swift 6.2) lets the deinitializer of a @MainActor class touch searchTask. In older versions, store the handle somewhere the deinitializer is allowed to reach, or cancel the task explicitly when the screen goes away.
Task-local values
A task-local value is like a thread-local variable for tasks. You declare it as a static property with @TaskLocal, and bind it for the duration of a closure with $name.withValue(_:operation:). All code called from that closure sees the value: child tasks and Task { } do, but Task.detached doesn't. That makes task-locals useful for request IDs, tracing and logging context, where passing a parameter through every function would be noise.
enum Request {
@TaskLocal static var id: String = "none"
}
func log(_ message: String) {
print("[\(Request.id)] \(message)")
}
func handle() async {
log("handling")
await Task { // inherits task-local values
log("in Task {}")
}.value
await Task.detached { // does not
log("in Task.detached")
}.value
}
@main
struct Main {
static func main() async {
log("startup")
await Request.$id.withValue("req-1") {
await handle()
Request.$id.withValue("req-1/retry") {
log("nested")
}
log("back")
}
log("done")
}
}
Output:
[none] startup
[req-1] handling
[req-1] in Task {}
[none] in Task.detached
[req-1/retry] nested
[req-1] back
[none] done
Task-local values are read-only. You can't assign Request.id = "x"; you can only bind a new value for a nested scope with withValue. When the scope ends, the previous value comes back. Outside any binding, you get the default from the declaration. The value type must be Sendable, because child tasks on other threads read it.
Task.immediate and task names (Swift 6.2)
A task created with Task { } doesn't start synchronously. It's scheduled, and it starts when its executor gets to it. Task.immediate instead runs the closure right away, synchronously, on the caller's executor, up to the first suspension point. After that it continues like a normal task. This matters when the first part of the work must happen before the calling function continues. One example is updating UI state from an event handler before the next event arrives.
Swift 6.2 also lets you give a task a name, for debugging and logging. Task.name reads the name of the current task:
@main
struct Main {
static func main() async {
print("1. before")
let normal = Task { print("3. Task {} body") }
print("2. after Task {}")
await normal.value
print("4. before")
let immediate = Task.immediate {
print("5. Task.immediate body, until first suspension")
await Task.yield()
print("7. Task.immediate resumed")
}
print("6. after Task.immediate")
await immediate.value
let named = Task(name: "thumbnail-42") {
print("running in task named \(Task.name ?? "nil")")
}
await named.value
print("handle name:", named.name ?? "nil")
print("unnamed:", Task.name ?? "nil")
}
}
Output:
1. before
2. after Task {}
3. Task {} body
4. before
5. Task.immediate body, until first suspension
6. after Task.immediate
7. Task.immediate resumed
running in task named thumbnail-42
handle name: thumbnail-42
unnamed: nil
The order is deterministic here. The main() of a @main type runs on the main actor, so Task { } inherits the main actor and can't start until main() suspends at await normal.value. Task.immediate ran its body up to Task.yield() before Task.immediate returned.
There is also Task.immediateDetached. Task groups have addImmediateTask, and the name: parameter is accepted by addTask too.
Summary
Task { }starts unstructured async work and returns aTask<Success, Failure>handle. Useawait task.value(ortask.result) to wait for it, andtask.cancel()to cancel it.Task { }inherits actor isolation, priority and task-locals.Task.detached { }inherits nothing. PreferTask { }.- Cancellation is cooperative. Check
Task.isCancelled, or calltry Task.checkCancellation()to throwCancellationError.Task.sleepand other async APIs throw it for you. - Don't hide cancellation with
try?in code that should stop when cancelled. - Use
withTaskCancellationHandlerto stop callback-based or blocking work as soon as the task is cancelled. - Cancelling a task cancels its child tasks, but not the unstructured tasks it created. Dropping a handle cancels nothing.
@TaskLocalvalues flow into child tasks andTask { }, and are bound withwithValue.- Swift 6.2 added
Task.immediate, which starts synchronously, and task names, which help with debugging.