title: iOS: when does end background task code block get invoked?
body: <p>I have a long running task that I want completed, even if the application gets pushed to the background. From the documentation I can see that the way to do this is to use the beginBackgroundTaskWithExpirationHandler: feature and asynchronously start a task running as in the following code snippet:</p>
  
  <pre><code>UIApplication* application = [UIApplicationsharedApplication];
  bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
      // Clean up any unfinished task business by marking where you.
      // stopped or ending the task outright.
  
      [application endBackgroundTask: bgTask];
      bgTask = UIBackgroundTaskInvalid;
  }];
  
  // Start the long-running task and return immediately.
  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  
      // Do the work associated with the task, preferably in chunks.
           for (int i = 0; i &lt; 3; i++){
  
          [self doChunkOfWork];
      }
  
      // end work
      [application endBackgroundTask:bgTask];
      bgTask = UIBackgroundTaskInvalid;
  });
  </code></pre>
  
  <p>Now I understand that the second code block gets executed asynchronously and once completed the application is notified and the tasks is marked as invalid, however, can anyone tell me under what circumstances the first code block gets executed and also how the first and second blocks get associated? Is it simply that because I have started a task and sequentially the next thing I do is call dispatch_async that the two blocks will be associated?</p>