如何dispatch_group_wait为dispatch_group_async异步块内 [英] How to dispatch_group_wait for dispatch_group_async inside an asynchronous block

查看:418
本文介绍了如何dispatch_group_wait为dispatch_group_async异步块内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有code,它看起来是这样的:

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];

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

Basically, display a loading animation HUD and start generating image thumbnails from an asset, then once it's done hide the HUD. I'm using a dispatch group since i want to make sure all the thumbnails are generated before i hide the HUD.

但是,当我运行它时,HUD将立即被开除。我猜这是因为 generateCGImagesAsynchronouslyForTimes的异步特性:completionHandler: - dispatch_group_wait 之前被称为第一个 dispatch_group_async 的completionHandler内。

But when i run it, the HUD gets dismissed immediately. 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.

什么是优雅的方式来解决这种情况呢?谢谢你。

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...

当该计数器为0时,它会调用块调用

When that counter is 0, it will call a block to invoke

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?

这篇关于如何dispatch_group_wait为dispatch_group_async异步块内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆