2014-01-21 46 views
0

beginBackgroundTaskWithExpirationHandler當我們執行某些操作時創建一個新線程。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];. 

當應用程序變爲背景時,這會導致任何問題嗎?

回答

0

這可能是一些錯誤,因爲-beginBackgroundTaskWithExpirationHandler:不會創建任何線程。它只標誌着你即將開始或剛剛開始的一些長期任務的開始。

這種方法可以從任何線程調用。在主線程上調用它作爲參數使用的到期處理程序。該處理程序用於清理並標記您正在執行的長時間運行任務的結束。

+0

我編輯了我的帖子。 [[iosMobileApplication getKeepAliveManager]運行];導致一個新的線程。 – deltaaruna

相關問題