When an iOS application goes to the background, are lengthy tasks paused?

Jackson Tale picture Jackson Tale · Jul 11, 2011 · Viewed 67k times · Source

Yes, I know if I wish my app to be responsive to users' multitasking actions, such as switch to another app, I should deal with

- (void)applicationWillResignActive:(UIApplication *)application
- (void)applicationDidBecomeActive:(UIApplication *)application

What if my app is doing a quite-long time consuming operation (like downloading a big file) and the user causes my app to enter the background? Will that operation automatically be suspended and resumed when the user comes back to my app?

What exactly will happen behind the scene when my app enters the background or resumes in the foreground?

What if when users let my app go to the background my app's execution is just in the middle of a method?

For e.g., my app is doing

for (int i = 1 to 10000K) {
    do some calculation;
}

When i== 500K, user switches to another app. What happens to the for-loop in my app?

Answer

Brad Larson picture Brad Larson · Jul 11, 2011

From the iOS App Programming Guide:

Your app delegate’s applicationDidEnterBackground: method has approximately 5 seconds to finish any tasks and return. In practice, this method should return as quickly as possible. If the method does not return before time runs out, your app is killed and purged from memory. If you still need more time to perform tasks, call the beginBackgroundTaskWithExpirationHandler: method to request background execution time and then start any long-running tasks in a secondary thread. Regardless of whether you start any background tasks, the applicationDidEnterBackground: method must still exit within 5 seconds.

If the long-running operation you describe above is on the main thread and it takes longer than 5 seconds to finish after your application heads to the background, your application will be killed. The main thread will be blocked and you won't have a chance to return from -applicationDidEnterBackground: in time.

If your task is running on a background thread (and it really should be, if it's taking long to execute), that thread appears to be paused if the application returns from -applicationDidEnterBackground: (according to the discussion in this answer). It will be resumed when the application is brought back to the foreground.

However, in the latter case you should still be prepared for your application to be terminated at any time while it's in the background by cleaning things up on your way to the background.