How to dispatch_group_wait for dispatch_group_async inside an asynchronous block

笑着哭i 提交于 2020-01-21 08:38:09

问题


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. I'm using a dispatch group since i want to make sure all the thumbnails are generated before i hide the HUD.

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.


回答1:


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

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?



来源:https://stackoverflow.com/questions/20133770/how-to-dispatch-group-wait-for-dispatch-group-async-inside-an-asynchronous-block

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