Hi,

I am migrating my code to use GCD blocks instead of NSOperations.

NSOperation has a -cancel method to thread-safely notify the
NSOperation thread that it needs to be canceled.

How do you do this for an async GCD block?

I.e. suppose I have the following code:

@implementation MyClass
- (void)myMethod
{
dispatch_async(
       dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
       ^{
                do_some_lengthy_cancelable_operation();
       });
}
@end

I need to be able to cancel do_some_lengthy_cancelable_operation() at
some point.

The first solution that comes to my mind is the following.

@interface MyClass <MyCancellableOperation>
{
  bool m_isCancelled
}
- (bool)isCancelled;
@end

@implementation MyClass
- (void)myMethod
{
dispatch_async(
       dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
       ^{
                do_some_lengthy_cancelable_operation(self);
       });
}
@end

void do_some_lengthy_cancelable_operation (id<MyCancellableOperation> operation)
{
      for (int i = 0; i <BIG_NUMBER; ++i)
      {
           if ([operation isCancelled])
           {
                 break;
           }
      }
}

But this seems a bit clunky (compared to the elegance of GCD code),
and also I'm not sure if it will be thread-safe to set m_isCancelled
from the main thread, while the async block may be racing to query it
(though it should be fine, setting a boolean variable should be
atomic).

Is there a better solution?

Thanks,

Oleg.
_______________________________________________

Cocoa-dev mailing list ([email protected])

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to [email protected]

Reply via email to