gpt4 book ai didi

ios - 嵌套的 dispatch_async(dispatch_async 在另一个 dispatch_async 中)

转载 作者:行者123 更新时间:2023-11-29 00:36:19 28 4
gpt4 key购买 nike

我如何在 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");

});

这是我的方法:

-(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");
});
}

我的输出是:
主要
结束
block 1
Block2
决赛
Block1结束
Block2结束
Block3

但我需要
主要
结束
block 1
Block2
Block1结束
Block2结束
Block3
最后的

最佳答案

您只需要收到您的 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;
}

关于ios - 嵌套的 dispatch_async(dispatch_async 在另一个 dispatch_async 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40526295/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com