当我的应用程序enterBackground我需要发送两个网络请求,但我不知道何时何地设置bgTask = UIBackgroundTaskInvalid;
来结束后台任务:
这是我的代码:
__block BOOL firstRequestFinished = NO;
__block BOOL secondRequestFinished = NO;
__block UIBackgroundTaskIdentifier bgTask = 0;
bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
//stopped the tasack
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
//发送第一个请求
[NSURLConnection sendAsynchronousRequest:request1 queue:[NSOperationQueue new]
completionHandler:^(NSURLResponse *response, NSData *_data, NSError *connectionError) {
firstRequestFinished = YES;
//stop task, just if secondRequestFinished
if(secondRequestFinished){
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}
}];
//发送第二个请求
[NSURLConnection sendAsynchronousRequest:request2 queue:[NSOperationQueue new]
completionHandler:^(NSURLResponse *response, NSData *_data, NSError *connectionError) {
secondRequestFinished = YES;
//stop task just if the firstrequest finsihed
if(firstRequestFinished)
{
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}
}];
什么打扰我,是在不同的线程中调用完成块,所以如果两者都被执行同时不会调用[application endBackgroundTask:bgTask]
,如何避免?
我知道这是一个罕见的案例,但我只需要知道如何解决它。
答案 0 :(得分:0)
将局部变量转换为原子属性,即线程安全,将修复它。
@property (atomic, readwrite) BOOL firstRequestFinished;
@property (atomic, readwrite) BOOL secondRequestFinished;
如果你有多个主题,那么setter&吸气者同时被召唤。原子属性锁定基础变量,保证get / set操作使用完整的值。