问题
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
回答1:
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);
来源:https://stackoverflow.com/questions/7077589/ios-how-to-be-notified-when-a-thread-using-gcd-ends-its-job