0

Once I start a queue it takes almost 3-4 minutes, In case I want to stop this queue on a button(cancel button) click then can I do so?? If yes then how ?

dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        @synchronized(self)
        {
            for (int i = 0; i < (4000); i++) {
                         (Some methods)
            }
        }
});

Can I stop or dismiss this thread?

Navnath Godse
  • 2,233
  • 2
  • 23
  • 32
shreeji
  • 65
  • 7

2 Answers2

2

First don't synchronize in a gcd block. Use serial queues instead.

That being said, there is no way to stop a gcd block, but there is a way around it. In your queue you have a loop: Using a boolean flag you can simply exit your loop and basically terminate the gcd block.

See an example here

Community
  • 1
  • 1
Lefteris
  • 14,550
  • 2
  • 56
  • 95
  • The loop thing is not enough because the task are async. Tasks that are already in the queue when you flag for interruption will be executed anyway. The idea is being able to cancel future and present tasks. – Duck Jun 10 '15 at 22:36
1

Your first issue is that you block the main thread by doing a dispatch_sync

BUT as an answer to your question:

you should use a NSOperationQueue. that can be suspended between operations easily

off the top of my head:

NSOperationQueue *_myQueue; //instance var

_myQueue = [[NSOperationQueue alloc] init]; //init it

_myQueue.suspended = (buttonPressed) ? YES : NO; //toggle it like you need

for (int i = 0; i < (4000); i++) {
   [_queue addOperationWithInvocation:NSInvocation for method to call];  
}
Community
  • 1
  • 1
Daij-Djan
  • 49,552
  • 17
  • 113
  • 135