Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Canceling a Dispatch Queue

I'm using Grand Central Dispatch in my application in order to run a method in the background. The method computes some mathematical data based on a user's input and it takes a little while to do so. Keep in mind it is not using the internet.

I run this background "compute" method (which is a dispatch queue) whenever the main view loads. The problem is that if the user switches views in the application while the method is running in the background, the application crashes.

Is there any way to "cancel" the queue/stop the code block from running when the user switches views? Another way to think of it is by looking at the iPhone Weather.app. When Weather loads, it downloads data in the background, and pressing the little info button in the corner while it's downloading doesn't crash the application.

Thanks!

queue = dispatch_queue_create("com.mycompany.myqueue", 0);

dispatch_async(queue, ^{  
    //make some complicated calculations
});
like image 493
spiralstairs Avatar asked Apr 06 '26 06:04

spiralstairs


1 Answers

Suspending the queue itself won't help you once the block has begun execution. But you could define a BOOL called 'cancel' with the __block qualifier, and then at appropriate stages of the calculation (at each iteration or other segment), you can check that 'cancel' is still NO before continuing.

like image 191
Firoze Lafeer Avatar answered Apr 08 '26 19:04

Firoze Lafeer