我的应用程序中有一些后台线程,其中一些 NSTimer
在 NSDefaultRunLoopMode
模式下运行。当我按下主页按钮时,应用程序进入后台。
如果我不在 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/