articles icon indicating copy to clipboard operation
articles copied to clipboard

Blocks on GCD and cancellation

Open barbaramartina opened this issue 9 years ago • 4 comments

Hi Mattt, I was reading the article about NSOperation in which you state the following: "Unlike a block scheduled on a GCD queue, an NSOperation can be cancelled" According to what I know there are some changes starting from iOS 8 and you can cancel blocks that have not still reached the head of the queue. Changes in dispatch You can look for dispatch_block_cancel. Thanks for the article!

barbaramartina avatar Jan 18 '16 13:01 barbaramartina

Thanks for pointing this out, @barbaramartina. I'll queue this up for a future update.

One important difference to keep in mind is that GCD block cancellation doesn't work for currently executing blocks, whereas operations can be canceled in flight.

mattt avatar Jul 17 '18 21:07 mattt

If NSOperationQueue is built on the top of GCD, how is possible that NSOperationQueue has a feature that GCD doesn't? (Unless this feature was inplemented manually by API developers)

Ricardo1980 avatar Jul 18 '18 07:07 Ricardo1980

@Ricardo1980 Not an unreasonable question. It's a difference in semantics: operation cancelation is merely advisory. Once an operation starts, it's up to the implementation to check the state of isCancelled (or respond to KVO notification) and take appropriate action. For example, a networking operation that downloads a large file might cancel the underlying request when cancel() is called on it. In contrast, I don't believe there's an equivalent mechanism for blocks without referencing external mutable state. However, operation-style cancellation is part of DispatchWorkItem, so that's a great alternative if you want to keep things in the GCD family.

For anyone interested in seeing how Operation works, the Swift implementation is open source: https://github.com/apple/swift-corelibs-foundation/blob/master/Foundation/Operation.swift

mattt avatar Jul 18 '18 09:07 mattt

Thanks a lot!

Ricardo1980 avatar Jul 18 '18 10:07 Ricardo1980