澄清cancelByProducingResumeData何时调用完成处理程序

时间:2015-10-28 15:46:21

标签: ios objective-c multithreading grand-central-dispatch dispatch-async

Apple文档有以下示例,用于获取后台执行时间,并在应用程序进入后台后执行某些任务。使用dispatch_async执行任务有什么好处?即当应用程序在后台时,在"主线程"上进行工作之间的区别是什么? vs"异步地在后台线程"?

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    bgTask = [application beginBackgroundTaskWithName:@"MyTask" expirationHandler:^{
    // Clean up any unfinished task business by marking where you
    // stopped or ending the task outright.
    [application endBackgroundTask:bgTask];
    bgTask = UIBackgroundTaskInvalid;
    }];

   // Start the long-running task and return immediately.
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

    // Do the work associated with the task, preferably in chunks.

     [application endBackgroundTask:bgTask];
     bgTask = UIBackgroundTaskInvalid;
    });
}

2 个答案:

答案 0 :(得分:0)

经过一些实验后,如果你不调用dispatch_async,我会看到两个问题。如果您正在执行长时间运行的任务(例如在while循环中执行某些操作),那么如果您尝试将其恢复到前台,则不会允许应用程序重新启动。此外,我发现即使应用程序从远端接收数据,也不会调用任何网络代理。

答案 1 :(得分:0)

根据文档,您有5秒时间执行applicationDidEnterBackground:中的任何任务并返回。如果您需要额外的时间 - 您必须使用beginBackgroundTaskWithName:

  

实际上,您应该从applicationDidEnterBackground:as返回   尽快。如果方法在时间运行之前没有返回   你的应用程序被终止并从内存中清除。

这就是为什么你应该通过beginBackgroundTaskWithName:调用请求额外的后台执行,并在某个线程上异步运行任务。通过这种方式,您将遵循“5秒”规则。