Mulithreading:只有在完成执行其他方法后才执行方法调用 [英] Mulithreading: executing method calls only after finished executing other method

查看:130
本文介绍了Mulithreading:只有在完成执行其他方法后才执行方法调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to process method asynchronously, as per requirements, once the first method has completed, only then the second method should start executing. The Problem is first method itself has code that runs on background thread.

我尝试了dispatch_semaphore_wait,但这也没有用。

I tried dispatch_semaphore_wait, but that didnt work either.

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本身在另一个这样的工作线程上运行

FirstMethod itself runs on another worker thread like this

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

 }];

达到目标的最佳途径是什么,我不能改变firstMethod的定义,因为它是由第三方提供的,并且也改变它意味着改变大量现有代码从这个方法被调用的地方

What is the best way to achieve it, I cannot change the definition of firstMethod as it provided by some 3rd party and also changing it means changing lots of existing code from where this method is being called

推荐答案

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

You can use a completion block. You just need to modify firstMethod this way:

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

然后以这种方式使用它:

And then use it this way:

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

这篇关于Mulithreading:只有在完成执行其他方法后才执行方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆