0

This is what my code looks like now and I want to call these methods in a serial manner:

-(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..

}

I believe I have to use dispatch_get_main_queue but I can't figure out how to implement this in the above case.

How do I submit [runner runThisMethodOnTheMainThreadUsing:thisParameter using:thisOtherParamater andUsing:thisOtherOneAsWell]; to the Main Thread, then return to the execution of the rest of my background methods and then get the main thread again if the next method in line needs it?

4

2 回答 2

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
    });
    });
});
于 2012-08-23T19:00:05.123 回答
1

你可以dispatch_get_main_queue像这样使用:

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

为了更好地理解dispatch检查这个链接

于 2012-08-23T19:11:41.943 回答