所以这个网页上有关于后台执行的例子:https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html#//apple_ref/doc/uid/TP40007072-CH4-SW1,这里是例子:苹果编程指南iOS背景执行指南的例子?
- (void)applicationDidEnterBackground:(UIApplication *)application {
bgTask = [application beginBackgroundTaskWithName:@"MyTask" expirationHandler:^{
// 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.
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
});
}
据说bgTask
在类作为变量定义。因此,每个类(对象)的实例都有一个bgTask
属性。如果applicationDidEnterBackground
在异步块完成之前被多次调用,是否存在竞态条件的危险?我的意思是bgTask
会改变它的值,而endBackgroundTask
将被调用新的任务值,而不是旧值?
这里不是更好的解决方案来做到这一点:
__block UIBackgroundTaskIdentifier bgTask;
调用beginBackgroundTaskWithName
过吗?
,你应该检查是否bgTask是不是无效,并分配给它新的价值之前结束它。 –
if(_bgTask!= UIBackgroundTaskInvalid) [[UIApplication sharedApplication] endBackgroundTask:_bgTask]; WEAK_SELF weakSelf = self; _bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^ {[UIApplication sharedApplication] endBackgroundTask:weakSelf.bgTask]; weakSelf.bgTask = UIBackgroundTaskInvalid; }]; –