iOS-如何在线程(使用GCD)结束工作时收到通知 [英] iOS - how to be notified when a thread (using GCD) ends it's job
本文介绍了iOS-如何在线程(使用GCD)结束工作时收到通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我开始使用GCD,我需要知道某个线程何时结束它的工作.
I'm start to use GCD, and I need to know when a certain thread has ended it's job.
我的代码:
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可以停止. 现在的样子,它在线程结束之前就停止了.
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.
谢谢
RL
推荐答案
我将建立一个组,并使用dispatch_group_wait
仅在计算完成后才继续.举个例子:
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);
或者,如果要防止回调阻止,请使用dispatch_group_notify
:
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);
这篇关于iOS-如何在线程(使用GCD)结束工作时收到通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文