Reputation: 177
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?
Upvotes: 2
Views: 2010
Reputation: 28688
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
}
Upvotes: 3
Reputation: 2860
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.)
Upvotes: 0