1

I'm start to use GCD, and I need to know when a certain thread has ended it's job.

My code:

dispatch_queue_t registerDeviceQueue = dispatch_queue_create("RegisterDevice", NULL);
dispatch_async(registerDeviceQueue, ^{
    [self registerDevice];

    dispatch_async(dispatch_get_main_queue(), ^{
        [aiRegisterDevice stopAnimating];
    });
});
dispatch_release(registerDeviceQueue);

I need to know when this tread has ended, so that the UIActivityView can stop. The way it is now, it's stops before the thread ends.

Thanks,

RL

Chris Mowforth
  • 6,689
  • 2
  • 26
  • 36
Rui Lopes
  • 2,562
  • 6
  • 34
  • 49
  • Are you calling `[aiRegisterDevice startAnimating]` **before** the first `dispatch_async()`? Where is that happening? – Grzegorz Adam Hankiewicz Aug 16 '11 at 11:52
  • Hi, yes. I'm calling in viewWillAppear. – Rui Lopes Aug 16 '11 at 11:53
  • Yes, I'm calling in -viewWillAppear. The question is that inside [self registerDevice], i call a web service, and receive data from it. And I see that the ActivityIndicator of the status bar works after my AI stops... That means that i still receive data... – Rui Lopes Aug 16 '11 at 11:55
  • And that would mean that `registerDevice` performs an asynchronous request, since `stopAnimating` won't be called until the method ends. You should call `stopAnimating` in your success/error download callback. It's difficult to really answer your question since `[self registerDevice]` could be doing anything really... – Grzegorz Adam Hankiewicz Aug 16 '11 at 12:24
  • So, it would be best that the class called has a delegate method, set this class as delegate, and then call the delegate to stop animating. Correct? – Rui Lopes Aug 16 '11 at 13:05

1 Answers1

6

I'd set up a group and use dispatch_group_wait to continue only when the computation has finished. To take your example:

dispatch_queue_t registerDeviceQueue = dispatch_queue_create("RegisterDevice", NULL);
dispatch_group_t group = dispatch_group_create();

dispatch_group_async(group, registerDeviceQueue, ^{
    [self registerDevice];
});

dispatch_group_wait(group, DISPATCH_TIME_FOREVER); // Block until we're ready
// Now we're good to call it:
[aiRegisterDevice stopAnimating];

dispatch_release(registerDeviceQueue);
dispatch_release(group);

Or, if you want to prevent the callback blocking use dispatch_group_notify:

dispatch_queue_t registerDeviceQueue = dispatch_queue_create("RegisterDevice", NULL);
dispatch_group_t group = dispatch_group_create();

dispatch_group_async(group, registerDeviceQueue, ^{
    [self registerDevice];
}); // In this version, the group won't block


// This block gets called asynchronously when the above code is done:
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
    [aiRegisterDevice stopAnimating];
});

dispatch_release(registerDeviceQueue);
dispatch_release(group);
Chris Mowforth
  • 6,689
  • 2
  • 26
  • 36