How do I know that all my tasks in Grand Central Dispatch are complete?

I need to submit multiple tasks to Grand Central Dispatch to run. First, some tasks will be completed, and some last.

How do I know that all my tasks in Grand Central Dispatch are complete?

Should I use a counter to record the number of completed tasks? Any reasonable method?

+9
ios
Mar 09 '12 at 10:08
source share
3 answers

You can use sending groups to receive notifications when all tasks are completed. This is an example from http://cocoasamurai.blogspot.com/2009/09/guide-to-blocks-grand-central-dispatch.html

dispatch_queue_t queue = dispatch_get_global_queue(0,0); dispatch_group_t group = dispatch_group_create(); dispatch_group_async(group,queue,^{ NSLog(@"Block 1"); }); dispatch_group_async(group,queue,^{ NSLog(@"Block 2"); }); dispatch_group_notify(group,queue,^{ NSLog(@"Final block is executed last after 1 and 2"); }); 
+22
Mar 09 '12 at 10:38
source share

If you want to control one task for execution at the end, you can use dispatch_group_t. If you want a single task to be performed not only after completing some tasks, but also to perform before some tasks, you can use dispatch_barrier_sync:

 dispatch_queue_t queue = dispatch_queue_create("com.example.gcd", DISPATCH_QUEUE_CONCURRENT); dispatch_async(queue, ^{ printf("1");}); dispatch_async(queue, ^{ printf("2");}); dispatch_barrier_sync(queue, ^{ printf("3");}); dispatch_async(queue, ^{ printf("4");}); dispatch_async(queue, ^{ printf("5");}); 

he can print

  12345 or 21354 or ... but 3 always after 1 and 2, and 3 always before 4 and 5 

If you want precise control over the order, you can use dispatch_sync or Serial Dispatch Queue or NSOperationQueue. If you are using NSOperationQueue, use the addDependency method to control the order of tasks:

 NSOperationQueue *queue = [[NSOperationQueue alloc] init]; NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"op 1"); }]; NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"op 2"); }]; NSBlockOperation *op3 = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"op 3"); }]; //op3 is executed last after op2,op2 after op1 [op2 addDependency:op1]; [op3 addDependency:op2]; [queue addOperation:op1]; [queue addOperation:op2]; [[NSOperationQueue mainQueue] addOperation:op3]; 

He will always print:

 op1 op2 op3 
+3
Feb 28 '15 at 14:00
source share

You can achieve this using GCD using DispatchGroup in swift 3 . You can be notified when all tasks are completed.

  let group = DispatchGroup() group.enter() run(after: 6) { print(" 6 seconds") group.leave() } group.enter() run(after: 4) { print(" 4 seconds") group.leave() } group.enter() run(after: 2) { print(" 2 seconds") group.leave() } group.enter() run(after: 1) { print(" 1 second") group.leave() } group.notify(queue: DispatchQueue.global(qos: .background)) { print("All async calls completed") } 
+1
Jun 15 '17 at 8:54 on
source share



All Articles