2

I've implemented a block that is dispatched asynchronously using GCD as follows:

__block BOOL retValue;
dispatch_async(dispatch_get_global_queue(0, 0), ^{
    retValue = [self GCDHandler:actionName WithServiceType:serviceType :arguments];
});

return retValue;

How do I cancel such a block if it is running for longer than I would like? Is there a way to cancel GCD-dispatched blocks, or provide a timeout to them?

Brad Larson
  • 170,088
  • 45
  • 397
  • 571
Baidyanath
  • 167
  • 1
  • 4
  • 14

2 Answers2

3

There is no built in way to cancel GCD blocks. They're rather set and forget. One way I've done this in the past is to provide 'tokens' for blocks.

- (NSString*)dispatchCancelable:(dispatch_block_t)block
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        if (!checkIfCanceled)
            block();
    }
    return blah; //Create a UUID or something
}

- (void)cancelBlock:(NSString*)token
{
   //Flag something to mark as canceled
}
Joshua Weinberg
  • 28,598
  • 2
  • 97
  • 90
  • This is 100% correct, though if block() is the long-running operation then checking beforehand is probably not going to give you the results you're looking for. The answer is to break block() up into smaller operations that can each be independently cancelled or put checks for "checkIfCancelled" into the block itself such that it can periodically make sure that it's still OK to run or, if not, unwind the operation in progress and return. – jkh Feb 16 '12 at 05:00
0

That depends on what your GCDHandler is doing. There's some pretty good videos about GCD on the Apple dev site - you might want to move up a layer (into Cocoa) and use NSOperationQueue and NSOperations (either your own subclass or NSBlockOperation). They're all built on top of GCD and the abstraction layer might be more appropriate for what you are trying to do (which you don't state - is it a network request? etc.)

Scott Corscadden
  • 2,831
  • 1
  • 25
  • 43