I am currently playing around with Grand Central Dispatch and discovered a class called DispatchWorkItem
. The documentation seems a little incomplete so I am not sure about using it the right way. I created the following snippet and expected something different. I expected that the item will be cancelled after calling cancel
on it. But the iteration continues for some reason. Any ideas what I am doing wrong? The code seems fine for me.
@IBAction func testDispatchItems() {
let queue = DispatchQueue.global(attributes:.qosUserInitiated)
let item = DispatchWorkItem { [weak self] in
for i in 0...10000000 {
print(i)
self?.heavyWork()
}
}
queue.async(execute: item)
queue.after(walltime: .now() + 2) {
item.cancel()
}
}
There is no asynchronous API where calling a "Cancel" method will cancel a running operation. In every single case, a "Cancel" method will do something so the operation can find out whether it is cancelled, and the operation must check this from time to time and then stop doing more work by itself.
I don't know the API in question, but typically it would be something like
GCD does not perform preemptive cancelations. So, to stop a work item that has already started, you have to test for cancelations yourself. In Swift,
cancel
theDispatchWorkItem
. In Objective-C, calldispatch_block_cancel
on the block you created withdispatch_block_create
. You can then test to see if was canceled or not withisCancelled
in Swift (known asdispatch_block_testcancel
in Objective-C).Or, in Objective-C: