A simple pattern for cancelling GCD blocks

Sometimes when using GCD, it’s useful to cancel a block that’s already been placed on a queue to be processed. You could have a field named “isCancelled” that the block can check for but if you have lots of blocks you’d have to have a field for each block (or a dictionary etc). It’s useful to just define the flag as a captured variable so that each block gets its own unique flag. Changing the cancel flag is done by providing the flag value as an argument to the block.

@interface FooClass()
{
void(^block)(BOOL);
}
@end

@implementation FooClass

-(void) foo
{
   BOOL isCancelled = NO;

   block = (BOOL cancel)
   {
       if (cancel || isCancelled)
       {
           isCancelled = YES;

           return;
       }
       
       doProcessing();
   }
}

@end
Add Comment Register



Leave a Reply

Your email address will not be published.


× 4 = thirty six

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>