Middle
Tell me about the cancellation mechanism in DispatchWorkItem.
sobes.tech AI
Answer from AI
DispatchWorkItem represents a block of code that can be scheduled for execution in a dispatch queue, and it can be canceled before it actually executes.
Cancellation is implemented via a flag inside the DispatchWorkItem. The cancellation mechanism is cooperative: DispatchWorkItem must regularly check its cancellation status.
When the cancel() method is called on a DispatchWorkItem, a cancellation flag is set. The actual interruption of execution occurs only if the code block inside the DispatchWorkItem checks this flag using the isCancelled property.
Example usage:
let task: DispatchWorkItem = DispatchWorkItem {
for i in 0..<100 {
guard !self.isCancelled else { // Check cancellation flag
print("Operation canceled at iteration \(i)")
return // End execution
}
// Perform useful work
Thread.sleep(forTimeInterval: 0.1) // Simulate a long operation
}
print("Operation completed")
}
DispatchQueue.global().async(execute: task)
// Cancel the task after 1 second
DispatchQueue.global().asyncAfter(deadline: .now() + 1) {
task.cancel()
}
Key points:
- Immediate cancellation is not guaranteed; it depends on how frequently
isCancelledis checked inside the block. - A canceled
DispatchWorkItemcan be queued, but its block will not execute ifisCancelledis checked before starting. - Calling
cancel()on aDispatchWorkItemthat has already completed or been canceled has no effect.
Properties:
| Property | Type | Description |
|---|---|---|
isCancelled |
Bool |
Returns true if the work has been canceled. |