How to cancel a worker thread in applicationDidEnterBackground on iOS
I've heavily researched for a proper solution but it didn't work out functional: My iPhone app updates data via NSURL requests on user demand. Each file loaded online is only 1.5k in size but one update can consist of 400 of such files. So I do the download stuff in a separate thread which is cancelable and during the update there is an UIAlertView with process indication and cancel button. The thing may run 1...3 minutes, so it can exceed the timeout the device is staying alive or other things happen and my app will go background.
When I do nothing when applicationDidEnterBackground is called, I realize that my app is suspended and also the worker thread. It wakes up and continues work when the app is in foreground again. So far so good. I get into trouble when I press the cancel button after being in foreground again - then the thread reacts as being cancelled (as it should) but immediately runs again and crashes at the end (with error codes somewhere deep in Apple frameworks). It works perfectly to cancel the thread as long as the app keeps staying in foreground - so my idea is to stop/cancel it when applicationDidEnterBackground is entered. I've tried some things to do so but each attempt ends in the fact that the worker thread is suspended at that moment applicationDidEnterBackground is called, so I can't cancel the thread and wait for that. One example I tried is this:
diagView* viewDiagCtrl = startDiag.diagViewControl;
if (viewDiagCtrl != nil && viewDiagCtrl.actionThread != nil)
{
// UIBackgroundTaskIdentifier bgTask is instance variable
NSAssert(self->bgTask == UIBackgroundTaskInvalid, nil);
bgTask = [application beginBackgroundTaskWithExpirationHandler:
^{
dispatch_async(dispatch_get_main_queue(),
^{
NSLog(@"stopping actions definitely");
[viewDiagCtrl stopBackGroundActivity:self];
[application endBackgroundTask:self->bgTask];
self->bgTask = UIBackgroundTask开发者_JAVA百科Invalid;
});
}];
dispatch_async(dispatch_get_main_queue(),
^{
// Start with 10ms time boxes
NSTimeInterval ti = 0.01;
while ([application backgroundTimeRemaining] > 1.0)
{
if (![viewDiagCtrl.actionThread isExecuting])
break;
NSDate* date = [NSDate dateWithTimeIntervalSinceNow:ti];
// Let the current run-loop do it's magif for one time-box.
[[NSRunLoop currentRunLoop] runMode: NSRunLoopCommonModes
beforeDate: date];
// Double the time box, for next try, max out at 1000ms.
ti = MIN(1.0, ti * 2);
}
[viewDiagCtrl stopBackGroundActivity:self];
[application endBackgroundTask:self->bgTask];
self->bgTask = UIBackgroundTaskInvalid;
});
}
I'm not experienced with the whole queue stuff and found such a construct somewhere. I assume that all things dispatched work in the main thread and the worker thread remains suspended so that I don't have any chance to cancel it. Any ideas to come around with that?
I've also read about attempts to do everything without multithreading - but I don't really appreciate that.Is there maybe some useful link to handle the "go background" situation properly?
You can wrap your thread work in the background thread like:
...
[self performSelectorInBackground:@selector(backgroundThread)
withObject:nil];
...
-(void)backgroundThread
{
// do a download once a minute in a background thread - dont let the system suspend us
while(true)
{
BOOL expire = NO;
bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{expire = YES;}];
while(!downloadComplete && !expire)
{
//do your multiple file downloads here;
}
[[UIApplication sharedApplication] endBackgroundTask:bgTask];
[NSThread sleepForTimeInterval:60];
}
}
What this will do is continue the task in progress which will continue when the app is backgrounded - I do this is several places in my heavily threaded/network intensive app.
AFAIK: You don't have to wait until the app is being backgrounded to call beginBackgroundTask - you should call it any time your app has a function it needs to complete without being interrupted/suspended.
I also use NSURLRequest with:
[request setNetworkServiceType:NSURLNetworkServiceTypeVoIP];
(and use the voip background mode in the supportedbackgroundmodes flag)
精彩评论