1

I know dispatch_async can handle thread.

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{  
    // handle things that takes a long time
    dispatch_async(dispatch_get_main_queue(), ^{  
        // update UI 
    });  
}); 

But How can I cancel it the thread?

For example:

I have two viewcontrollers- AViewController and BViewController, A->present B, and a button to dismiss B.

I'll do myMethod in BViewController, the things is I want to dismiss B when exec myMethod, so I use dispatch_async, it did dismiss from B to A. but after going back to AViewController, here comes the audio.

How can I stop the myMethod after dismiss method exec immediately?

- (void)myMethod {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{  
        // handles thing A
        // play a audio
        dispatch_async(dispatch_get_main_queue(), ^{  
            // update UI 
        });  
    }); 
}
ronan
  • 1,611
  • 13
  • 20
  • possible duplicate of [How to stop a thread created with dispatch\_async?](http://stackoverflow.com/questions/17671828/how-to-stop-a-thread-created-with-dispatch-async) – Mohamed Elkassas Sep 07 '15 at 04:24

1 Answers1

2

What you need for this is not GCD and dispatch_async, but an NSOperation. It is a high-level wrapper around GCD that allows you to have references to your async operations, check their status, cancel them, etc.

I recommend using a very handy subclass named NSBlockOperation. You should keep a reference to your operation in your class, and if you need to cancel it, just call [self.myOperation cancel].

TotoroTotoro
  • 17,524
  • 4
  • 45
  • 76