iOS - how to be notified when a thread (using GCD) ends it's job

青春壹個敷衍的年華 提交于 2019-11-29 15:48:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!