我开始使用GCD,我需要知道某个线程何时结束工作。
我的代码:
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);
我需要知道此步结束的时间,以便UIActivityView可以停止。
现在的样子,它在线程结束之前就停止了。
谢谢,
RL
最佳答案
我将建立一个组,并使用dispatch_group_wait
仅在计算完成后才继续。举个例子:
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);
或者,如果您想防止回调阻塞,请使用
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);
关于objective-c - iOS-如何在线程(使用GCD)结束工作时收到通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7077589/