0

Im using GCD blocks To call My service in the background thread.I want to provide a cancel button for the user to cancel process/Loading Svc.

How can I Stop the Execution when user Cancel’s if it's not possible Guide me to acheive same functionalty

 dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Add code here to do background processing
//
//
dispatch_async( dispatch_get_main_queue(), ^{
    // Add code here to update the UI/send notifications based on the
    // results of the background processing
});
});

Thank you

siva
  • 251
  • 2
  • 16
  • 1
    possible duplicate of [How do I kill/suspend/close an asyncronous block in GCD?](http://stackoverflow.com/questions/9294139/how-do-i-kill-suspend-close-an-asyncronous-block-in-gcd) – Shai Feb 17 '15 at 09:47

1 Answers1

2

You could consider adding a level of abstraction to GCD and use NSOperation. It provides a native cancel method however never stops execution of your code immediately.

MrBr
  • 1,884
  • 2
  • 24
  • 38
  • 1
    You misunderstand how NSOperation works. The code of your operation subclass has to check `-isCancelled` and return early. There is no practical way (i.e. without leaking any heap allocated objects created by the thread) to forcibly cancel a block submitted to GCD which is currently executing on a thread (or an NSOperation.) NSOperation provides API to make it easier to support cancellation but you still have to check the flag and return early, after cleaning up any resources your operation acquired. – ipmcc Feb 17 '15 at 15:23