pengwang
pengwang

Reputation: 19956

break Grand Central Dispatch run

i use

 dispatch_async(getDataQueue,^{
    //do many work task A
    dispatch_aysnc (mainQueue, ^{
    //do
};
}
)

if i press back key,and the gcd not finished its task A,i want to break the dispatch_async.how to do

Upvotes: 0

Views: 173

Answers (2)

borrrden
borrrden

Reputation: 33421

You cannot do this. One of the fundamental truths about GCD is that once you dispatch a block, it will run no matter what as long as the queue is not suspended. If you need cancelable async operations, you will need to use NSOperation

Upvotes: 0

trojanfoe
trojanfoe

Reputation: 122391

You could use a flag to continue working all the time it's false:

// Somewhere accessible from the task's block and from the view controller
__block BOOL quit = NO;

dispatch_async(getDataQueue,^{
    dispatch_aysnc (mainQueue, ^{

        if (!quit)
        {
            // do first thing
        }

        if (!quit)
        {
             // do second thing
        }

        while (!quit)
        {
            // do lots of things
        }

    });
});

And then you can stop the background task simply doing:

quit = YES;

This is the preferred method of stopping any background task anyway as it allows the task to perform clean-up without before forced to terminate.

Upvotes: 3

Related Questions