简体   繁体   English

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

[英]How to dispatch_group_wait for dispatch_group_async inside an asynchronous block

I have code that looks something like this: 我的代码看起来像这样:

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

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

Basically, display a loading animation HUD and start generating image thumbnails from an asset, then once it's done hide the HUD. 基本上,显示加载动画HUD并开始从资产生成图像缩略图,然后一旦完成隐藏HUD。 I'm using a dispatch group since i want to make sure all the thumbnails are generated before i hide the HUD. 我正在使用调度组,因为我想确保在隐藏HUD之前生成所有缩略图。

But when i run it, the HUD gets dismissed immediately. 但是当我运行它时,HUD会立即被解雇。 I'm guessing this is because of the asynchronous nature of the generateCGImagesAsynchronouslyForTimes: completionHandler: -- dispatch_group_wait is called before the first dispatch_group_async inside the completionHandler. 我猜这是因为异步性质generateCGImagesAsynchronouslyForTimes: completionHandler: - dispatch_group_wait是第一之前调用dispatch_group_async的completionHandler内。

What is a graceful way to get around this situation? 什么是一种优雅的方式来解决这种情况? Thanks. 谢谢。

Think of this method as a static counter available to threads, so when you enter a group the counter increments, and when that block returns, decrements... 可以将此方法视为线程可用的静态计数器,因此当您输入组时,计数器会递增,并且当该块返回时,递减...

When that counter is 0, it will call a block to invoke 当该计数器为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
});

Is that what you were thinking of? 这是你在想什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM