GCD - 如何在主线程上等待在主队列上执行的异步回调

时间:2014-06-27 17:34:43

标签: objective-c multithreading grand-central-dispatch completionhandler

我想一个接一个地执行2个块,其中每个块都是异步执行的。

例如

[someMethodWithCompletionHandler:^() {
  // do something in the completion handler
}];

[anotherMethodWithCompletionHandler:^ {
  // do something else in the completion handler after the first method completes
}];

现在,我需要' anotherMethodWithCompletionHandler'在' someMethodWithCompletionHandler'之后发生完成(包括其完成处理程序)

我会定期创建一个dispatch_group并在两个方法之间等待(我不能将这两个方法嵌套在另一个完成处理程序中,因为它需要移动很多代码)

但问题是在主线程中调用了第一个完成处理程序块(通过方法本身调用主线程中的块),因此我无法有效地创建阻塞主线程的dispatch_group。 / p>

所以线程状态看起来像这样

// main thread here

[self doFirstPortionOfWork];

// main thread here
[self doSecondPortionOfWork];


-(void)doFirstPortionOfWork
{
.. a lot of stuff happening
  [someMethodWithCompletionHandler:^{
  // this is the main thread
  }];
// would like to block the return here until the completion handler finishes
}

-(void)doSecondPortionOfWork
{
... a lot of work here
  [anotherMethodWithCompletionHandler^{
  // this is also called into the main thread
  }];
// would like to block the return here until the completion handler finishes
}

那么我怎么能通过求助于大量的嵌套方法并且能够阻塞主线程直到完成所有这些呢?

1 个答案:

答案 0 :(得分:1)

主线程与主队列相同

无法在主线程上等待主线程中的后续工作。你阻碍了未来的工作。

你可以这样做:

[someMethodWithCompletionHandler:^() {
    // do something in the completion handler
    [anotherMethodWithCompletionHandler:^ {
       // do something else in the completion handler after the first method completes
    }];
}];