When does Task.isCancelled become true?
I ask the question because I am hitting a Task 1: Assertion failed below in onCancel: {...}.
private func move (_ direction: String) async throws {
var times = Int.random (in: 3..<8)
try await withTaskCancellationHandler {
print (direction, "...")
while times > 0 {
if Task.isCancelled {
print ("cancelled", direction)
break
}
else {
try await Task.sleep (until: .now + .seconds (Int.random (in: 1..<3)))
times -= 1
}
}
} onCancel: {
print ("onCacel", direction)
assert (Task.isCancelled) // Task 1: Assertion failed
}
if times == 0 {
print ("completed", direction)
}
}
withTaskCancellationHandler (operation:onCancel:isolation:)Execute an operation with a cancellation handler that’s immediately invoked if the current task is canceled.
Discussion
This differs from the operation cooperatively checking for cancellation and reacting to it in that the cancellation handler is always and immediately invoked when the task is canceled. For example, even if the operation is running code that never checks for cancellation, a cancellation handler still runs and provides a chance to run some cleanup code: