带有当前线程的binbackgroundTaskWithExpirationHandler



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

当应用程序进行后台时,这会引起任何问题吗?

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

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

相关内容

  • 没有找到相关文章

最新更新