使用 GCD 时,我们希望等到两个异步块执行完毕后再继续执行下一步。最好的方法是什么?
我们尝试了以下方法,但似乎不起作用:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ { // block1 }); dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ { // block2 }); // wait until both the block1 and block2 are done before start block3 // how to do that? dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ { // block3 });
使用调度组:请参阅此处的示例,Apple’s iOS Developer Library’s Concurrency Programming Guide 的“调度队列”一章中的“等待队列任务组”
您的示例可能如下所示:
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"); }); // only for non-ARC projects, handled automatically in ARC-enabled projects. dispatch_release(group);
并且可以产生这样的输出:
2012-08-11 16:10:18.049 Dispatch[11858:1e03] Block1 2012-08-11 16:10:18.052 Dispatch[11858:1d03] Block2 2012-08-11 16:10:23.051 Dispatch[11858:1e03] Block1 End 2012-08-11 16:10:26.053 Dispatch[11858:1d03] Block2 End 2012-08-11 16:10:26.054 Dispatch[11858:1d03] Block3