multithreading:只有在完成执行其他方法后才执行方法调用

我试图按照要求asynchronous处理方法,一旦第一个方法完成,只有第二个方法应该开始执行。 问题是第一个方法本身具有在后台线程上运行的代码。

我试过dispatch_semaphore_wait,但也没有工作。

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0); dispatch_group_t group = dispatch_group_create(); dispatch_group_async(group, queue, ^{ [self firstMethod]; NSLog(@"firstMethod Done"); }); dispatch_group_notify(group, queue, ^ { NSLog(@"1st method completed"); NSLog(@"2nd method starting"); [self secondMethod]; }); 

FirstMethod本身就像这样在另一个工作线程上运行

 -(void)firstMethod { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ //processing here..... }]; 

什么是最好的方法来实现它,我不能改变一些第三方提供的firstMethod的定义,也改变它意味着改变这个方法被调用的地方现有的代码很多

您可以使用完成块。 你只需要这样修改firstMethod:

 - (void)firstMethodWithOnComplete:(void (^)(void))onComplete { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ //processing here..... onComplete(); }); } 

然后用这个方法:

 [self firstMethodWithOnComplete:^{ [self secondMethod]; }]; 

调度单个队列并按顺序调用您的方法

 dispatch_group_async(group, queue, ^{ [self firstMethod]; NSLog(@"firstMethod Done"); [self secondmethod]; }); 

或者你可能派遣一组3个并发队列(这是一个疯狂的猜测)