objective-cobjective-c-blocksgrand-central-dispatchuibackgroundtask

Dispatch call to main queue inside UIBackgroundTaskIdentifier


I am running a certain task under UIBackgroundTaskIdentifier since i want to run it in background. My code looks something like this.

-(void) function
{

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{

        UIBackgroundTaskIdentifier BGIdentifier = [[UIApplication sharedApplication]   beginBackgroundTaskWithExpirationHandler:^{}];     

        // some processing

        dispatch_async(dispatch_get_main_queue(), ^{
            // some UI stuff
        });

        // some processing again

        dispatch_async(dispatch_get_main_queue(), ^{
            // some UI stuff again
        });

        [[UIApplication sharedApplication] endBackgroundTask:BGIdentifier];        
    });
}

So I have two questions.

  1. If my app goes to background while some processing is happening what will happen to the dispatch_async calls to main queue?
  2. Is this a good design ?

Solution

  • In answer to your question, those dispatched blocks to the main queue operate as you'd expect, and everything will work fine, and when the app is brought back into the foreground, you'll see the UI updated properly. Two caveats:

    1. You will want to ensure that the endBackgroundTask is not invoked before the final dispatch is done. You can achieve this by either:

      • Make that final UI dispatch synchronous; or

      • Include the endBackgroundTask as the last item in the last block you dispatch to the main queue.

      But the timing of this endBackgroundTask is important, you want to make sure you update your UI before you flag your background task as complete and indicate that it may be suspended.

    2. I don't know how you want to handle a failure to complete the background task, but generally you would call endBackgroundTask in the expiration handler, too, because otherwise the app will be summarily terminated if the background task didn't complete in the allotted time. See the Executing a Finite-Length Task in the Background of the App States and Multitasking chapter of the iOS App Programming Guide for an example.