嵌套dispatch_async(另一个dispatch_async中的dispatch_async)

时间:2016-11-10 11:18:30

标签: ios objective-c xcode nested dispatch-async

我如何在dispatch_async

内拨打dispatch_async来电
dispatch_group_t downloadQueue = dispatch_group_create();
dispatch_group_async(downloadQueue,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {

NSLog(@"Main");
[NSThread sleepForTimeInterval:5.0];
NSLog(@"End");

    [self myMethod];

});
dispatch_group_notify(downloadQueue,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0), ^ {

    NSLog(@"FINAL");

});

这是myMethod:

-(void)myMethod
{
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_async(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
        // block1
        NSLog(@"Block1");
        [NSThread sleepForTimeInterval:5.0];
        NSLog(@"Block1 End");
    });
    dispatch_group_async(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
        // block2
        NSLog(@"Block2");
        [NSThread sleepForTimeInterval:8.0];
        NSLog(@"Block2 End");
    });

    dispatch_group_notify(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
        // block3
        NSLog(@"Block3");
    });
}

,我的输出是:

结束
块1
块2
FINAL
Block1 End
Block2 End
块3

但我需要

结束
块1
块2
Block1 End
Block2 End
块3
FINAL

2 个答案:

答案 0 :(得分:1)

您只需要通知您的一组myMethod。你的代码将是:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {

    NSLog(@"Main");
    [NSThread sleepForTimeInterval:5.0];
    NSLog(@"End");

    dispatch_group_notify([self myMethod],dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0), ^ {

        NSLog(@"FINAL");

    });
});

-(dispatch_group_t)myMethod{

    dispatch_group_t group = dispatch_group_create();

    dispatch_group_async(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
        // block1
        NSLog(@"Block1");
        [NSThread sleepForTimeInterval:5.0];
        NSLog(@"Block1 End");
    });


    dispatch_group_async(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
        // block2
        NSLog(@"Block2");
        [NSThread sleepForTimeInterval:8.0];
        NSLog(@"Block2 End");
    });

    dispatch_group_notify(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
        // block3
        NSLog(@"Block3");
    });
    return group;
}

答案 1 :(得分:0)

您可以在myMethod中使用 dispatch_group_wait ,而不是dispatch_group_notify。这样,只有当dispatch_group_async都完成执行时,您的方法才会返回。