ios - 当后台时间到期时,为什么不是所有后台线程都被挂起?

标签 ios objective-c multithreading

我的应用程序中有一些后台线程,其中一些 NSTimerNSDefaultRunLoopMode 模式下运行。当我按下主页按钮时,应用程序进入后台。

如果我不在 applicationDidEnterBackground: 中调用 beginBackgroundTaskWithExpirationHandler:,当应用程序处于后台时,线程会暂停。但是,如果我调用 beginBackgroundTaskWithExpirationHandler:,线程即使在过期处理程序返回后也不会暂停

为什么后台线程在一种情况下继续运行而在另一种情况下却不运行?在第二种情况下,后台线程什么时候会被挂起?

最佳答案

根据这份文件beginBackgroundTaskWithExpirationHandler:

This method lets your app continue to run for a period of time after it transitions to the background.

这就是为什么如果您在 applicationDidEnterBackground: 中调用 beginBackgroundTaskWithExpirationHandler:,线程不会被挂起。

Each call to this method must be balanced by a matching call to the endBackgroundTask: method. Apps running background tasks have a finite amount of time in which to run them. (You can find out how much time is available using the backgroundTimeRemaining property.) If you do not call endBackgroundTask: for each task before time expires, the system kills the app. If you provide a block object in the handler parameter, the system calls your handler before time expires to give you a chance to end the task.

因此,在第二种情况下,当您使用 beginBackgroundTaskWithExpirationHandler: 时,通过在 endBackgroundTask: 中添加 endBackgroundTask:过期处理程序。

关于ios - 当后台时间到期时,为什么不是所有后台线程都被挂起?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47049054/

相关文章:

ios - 在宏中使用时使用未声明的标识符 FLT_MAX

ios - 从昨天开始无法将存档上传到应用商店

iphone - 用两个 UIImageView 保存一个图像,其中有两个图像 - ios

multithreading - Erlang在运行并发任务时没有使用所有CPU核心,为什么?

iOS - 将 BLE 设备连接到应用程序和 iOS

ios - defaultPrefs 不更新

objective-c - NSMutableSet不添加对象

iphone - 单击 UISwitch 时选择 UITableView 的行

c++ - 将 C++ 函数对象作为线程例程传递给 pthread_create 函数

JavaScript 执行引擎未指定?