Predict the output
The task is cancelled after about 250 ms. What prints?
let task = Task {
for i in 1...5 {
print("step \(i)")
try? await Task.sleep(for: .milliseconds(100))
}
print("done")
}
try await Task.sleep(for: .milliseconds(250))
task.cancel()Hint 1 of 2
What does try? do with an error?
Hint 2 of 2
Does cancel() stop code by force?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: B All five steps and done; steps 4 and 5 print almost instantly after the cancel
Correct. After the cancel, each Task.sleep throws at once, try? swallows the error, and the loop keeps going.
Why not the others?
- A step 1, step 2, step 3, and nothing else.
cancel()doesn't stop the task. It only sets a flag that code must check. - C step 1 to step 3, then done. Nothing breaks out of the loop. That would need a cancellation check or a
trythat propagates. - D The program crashes with CancellationError.
try?turns the thrown error intonil, so nothing propagates.
Text version
| Version | What runs when | Finishes at |
|---|---|---|
| Without cancel |
| t = 0.5 s |
| Cancel at 0.25 s |
| t = 0.25 s |