【问题标题】:Mulithreading: executing method calls only after finished executing other method多线程:仅在执行完其他方法后才调用执行方法
【发布时间】:2013-05-09 22:09:06
【问题描述】:

我正在尝试异步处理方法,根据要求,一旦第一个方法完成,第二个方法才应该开始执行。问题是第一种方法本身具有在后台线程上运行的代码。

我尝试了 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 的定义,因为它是由某些第 3 方提供的,而且更改它意味着更改调用此方法的大量现有代码

【问题讨论】:

  • 除非第 3 方库提供某种方法来检测该私有块何时完成执行,否则基本上无法执行您所要求的操作。是吗?
  • rob:不,它不提供任何方法来查找该私有块何时完成
  • 你能总结一下私有异步块的作用吗?特别注意任何文件系统/网络交互。
  • 有关执行异步任务的通用方法,当它们按顺序完成时会报告,请参阅stackoverflow.com/questions/16226727/…

标签: ios objective-c multithreading objective-c-blocks grand-central-dispatch


【解决方案1】:

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

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

然后这样使用:

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

【讨论】:

  • 似乎是不错的替代方法,但 firstMethod 位于不同的库中,修改它需要在很多类中进行更改。还有其他解决办法吗?
  • 向实现 firstMethod 的类添加属性会更容易吗?在这种情况下,您可以使用委托模式。如果需要,我可以详细说明。
【解决方案2】:

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

dispatch_group_async(group, queue, ^{

            [self firstMethod];
            NSLog(@"firstMethod Done");
           [self secondmethod];

        });

或者你可以调度一组 3 个并发队列(这是一个疯狂的猜测)

【讨论】:

  • 这不起作用,因为 firstMethod 在其定义中有自己的 dispatch_async 调用,并且 [self secondmethod];不会等待 [self firstMethod];完成
猜你喜欢
  • 2018-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-19
  • 2020-01-27
相关资源
最近更新 更多