我如何在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
答案 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都完成执行时,您的方法才会返回。