如何在异步块内调度dispatch_group_async for dispatch_group_async

时间:2013-11-21 23:04:54

标签: ios objective-c multithreading asynchronous grand-central-dispatch

我的代码看起来像这样:

[SVProgressHUD show];
[imageGenerator generateCGImagesAsynchronouslyForTimes:times
                completionHandler:^(CMTime requestedTime, ...) {
                    dispatch_group_async(queueGroup, queue, ^{
                        // Do stuff
                });
}];

dispatch_group_wait(queueGroup, DISPATCH_TIME_FOREVER);
[SVProgressHUD dismiss];

基本上,显示加载动画HUD并开始从资产生成图像缩略图,然后一旦完成隐藏HUD。我正在使用调度组,因为我想确保在隐藏HUD之前生成所有缩略图。

但是当我运行它时,HUD会立即被解雇。我猜这是因为generateCGImagesAsynchronouslyForTimes: completionHandler: - dispatch_group_wait的异步性质在completionHandler中的第一个dispatch_group_async之前被调用。

解决这种情况的优雅方法是什么?感谢。

1 个答案:

答案 0 :(得分:9)

将此方法视为线程可用的静态计数器,因此当您输入组时,计数器会递增,当该块返回时,会递减...

当该计数器为0时,它将调用一个块来调用

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_t group = dispatch_group_create();

while(someCondition)
{
    dispatch_group_enter(group);
   [SomeClassThatLoadsOffTheInternet getMyImages:^{

        // do something with these.
        dispatch_group_leave(group);

    });
}

dispatch_group_notify(group, queue, ^{
    // do something when all images have loaded
});

这是你在想什么?