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

Vla*_*lad 3 multithreading asynchronous objective-c grand-central-dispatch ios

我的代码看起来像这样:

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

dispatch_group_wait(queueGroup, DISPATCH_TIME_FOREVER);
[SVProgressHUD dismiss];
Run Code Online (Sandbox Code Playgroud)

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

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

什么是一种优雅的方式来解决这种情况?谢谢.

cre*_*orn 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
});
Run Code Online (Sandbox Code Playgroud)

这是你在想什么?