从后台线程上执行的其他一些方法中执行主线程上的方法?

时间:2012-08-23 18:56:18

标签: objective-c ios multithreading nsoperationqueue

这就是我的代码现在看起来像,我希望以串行的方式调用这些方法:

-(void) methodOnBackThread // this method will run on a background thread
{
    [runner runThisMethod]; // and this will run on the same background thread as well

    [runner runThisOtherMethod]; // and so will this one

    // but I want this one to run on the main thread :       
    [runner runThisMethodOnTheMainThreadUsing:thisParameter using:thisOtherParamater andUsing:thisOtherOneAsWell]; 

    [runner runThisOtherMethod]; // this one will run on the background thread as well


     // but I want this one to run on the main thread :       
    [runner runThisMethodOnTheMainThreadUsing:thisParameter using:thisOtherParamater andUsing:thisOtherOneAsWell]; 

    [runner runThisOtherMethod]; // this one will run on the background thread as well

    // etc..

}

我相信我必须使用dispatch_get_main_queue但我无法弄清楚如何在上述情况下实现这一点。

如何将[runner runThisMethodOnTheMainThreadUsing:thisParameter using:thisOtherParamater andUsing:thisOtherOneAsWell];提交给主线程,然后返回执行其余的后台方法,然后再次获取主线程,如果下一个方法需要它?

2 个答案:

答案 0 :(得分:3)

如果您的目标是iOS4及以上,则使用大型中央调度。你可以这样做:

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    //do some stuff here in the background
    dispatch_async(dispatch_get_main_queue(), ^{
        //do some stuff here in the main thread
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
           //do some stuff here in the background after finishing calling a method on the main thread
    });
    });
});

答案 1 :(得分:1)

您可以使用dispatch_get_main_queue之类的:

dispatch_async(dispatch_get_main_queue(), ^{
        if (backgroundTask != UIBackgroundTaskInvalid)
        {
            [runner runThisMethodOnTheMainThreadUsing:thisParameter using:thisOtherParamater andUsing:thisOtherOneAsWell];
        }
    });

要更好地了解dispatch,请查看此link