Mulithreading: executing method calls only after finished executing other method

六眼飞鱼酱① 提交于 2019-12-20 10:56:06

问题


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.

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 itself runs on another worker thread like this

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

 }];

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


回答1:


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];
}];



回答2:


Dispatch a Single Queue and call your Methods in order

dispatch_group_async(group, queue, ^{

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

        });

Or you might dispatch a group of 3 concurrent queues(This is a Wild guess)



来源:https://stackoverflow.com/questions/16471952/mulithreading-executing-method-calls-only-after-finished-executing-other-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!