Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I know all my tasks in Grand Central Dispatch finished?

Tags:

ios

I need to send multiple tasks to Grand Central Dispatch to run. Some tasks will finish first, while some will finish last.

How do I know all my tasks in Grand Central Dispatch finished?

Should I use a counter to record the number of tasks finished? Any smarter method?

like image 537
user403015 Avatar asked Mar 09 '12 10:03

user403015


2 Answers

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

 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")
}
like image 86
Abhijith Avatar answered Mar 07 '23 08:03

Abhijith


You can use dispatch groups to be notified when all tasks 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");
});
like image 26
Martin Ullrich Avatar answered Mar 07 '23 08:03

Martin Ullrich