0

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];. 

当应用程序进入后台时,这会导致任何问题吗?

4

1 回答 1

1

这可能是一些错误,因为-beginBackgroundTaskWithExpirationHandler:不创建任何线程。它仅标志着您即将开始或刚刚开始的一些长期运行的任务的开始。

可以从任何线程调用此方法。它作为参数的过期处理程序在主线程上调用。此处理程序用于清理并标记您正在执行的长时间运行的任务的结束。

于 2014-01-21T14:46:44.893 回答