【发布时间】:2014-01-21 14:29:12
【问题描述】:
beginBackgroundTaskWithExpirationHandler 在我们执行某些操作时创建一个新线程。
我可以使用现有线程执行某些操作吗?
因为beginBackgroundTaskWithExpirationHandler 生成的新线程在恢复时会给我的应用程序带来一些问题。所以我将一个现有线程的实例传递给beginBackgroundTaskWithExpirationHandler,并使用现有线程调用所需的方法。可以在 beginBackgroundTaskWithExpirationHandler 中使用现有线程吗?
会不会有什么问题?
- (void)applicationDidEnterBackground:(UIApplication *)application {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
IOSMobilePOSApplication *app = [IOSMobilePOSApplication getInstance];
if ([app keepAliveMessage]) {
if([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)])
{
[Logger log:@"Multitasking Supported"];
background_task = [application beginBackgroundTaskWithExpirationHandler:^ {
[Logger log:@"Background maximum time exeeded."];
IOSMobilePOSApplication *iosMobileApplication = [IOSMobilePOSApplication getInstance];
[[iosMobileApplication getKeepAliveManager] stop];
//Clean up code. Tell the system that we are done.
[application endBackgroundTask: background_task];
background_task = UIBackgroundTaskInvalid;
}];
//To make the code block asynchronous
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//### background task starts
[Logger log:@"Running in the background"];
IOSMobilePOSApplication *iosMobileApplication = [IOSMobilePOSApplication getInstance];
[[iosMobileApplication getKeepAliveManager] setEnabled:true];
[[iosMobileApplication getKeepAliveManager] performSelector:@selector(run) onThread:[[iosMobileApplication getKeepAliveManager] runingThread] withObject:NULL waitUntilDone:NO];
isStarted = true;
//#### background task ends
//Clean up code. Tell the system that we are done.
[application endBackgroundTask: background_task];
background_task = UIBackgroundTaskInvalid;
});
}
else
{
[Logger log:@"Multitasking Not Supported"];
}
}
}
这里 [[iosMobileApplication getKeepAliveManager] run]; 导致新线程启动,并在我的代码中导致线程同步问题。所以我添加了代码来代替上面提到的行。
[[iosMobileApplication getKeepAliveManager] performSelector:@selector(run) onThread:[[iosMobileApplication getKeepAliveManager] runingThread] withObject:NULL waitUntilDone:NO];.
当应用程序进入后台时,这会导致任何问题吗?
【问题讨论】:
标签: objective-c multithreading background-thread