ConcurrencyMidOpen-ended
How do you cancel a running `Task`?
Explanation & Code
Answer: Tasks support cooperative cancellation — you cancel from outside, and the task must check for cancellation and stop itself.
Code Example:
// Hold a reference to cancel it
let task = Task {
for i in 0..<100 {
try Task.checkCancellation() // throws CancellationError if cancelled
await processItem(i)
}
}
// Cancel from outside
task.cancel()
// Checking cancellation without throwing
Task {
while !Task.isCancelled {
await doWork()
}
}
// async APIs like URLSession respect cancellation automatically
Task {
do {
let (data, _) = try await URLSession.shared.data(from: url)
} catch is CancellationError {
print("Task was cancelled")
}
}
Rate your understanding: