在GCD串行队列上安排和使NSTimers无效是否安全? [英] Is it safe to schedule and invalidate NSTimers on a GCD serial queue?

查看:162
本文介绍了在GCD串行队列上安排和使NSTimers无效是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这样做的正确方法是什么? NSTimer 文档说明了这一点:

What's the right way to do this? The NSTimer documentation says this:


特别注意事项

您必须从安装了计时器的
上的线程发送此消息。如果您从另一个
线程发送此消息,则与该计时器关联的输入源可能不会从其运行循环中移除
,这可能会阻止该线程正确退出

You must send this message from the thread on which the timer was installed. If you send this message from another thread, the input source associated with the timer may not be removed from its run loop, which could prevent the thread from exiting properly.

由于 GCD 不能保证串行队列总是在同一个队列上运行块线程,什么是确保您在同一个线程上安排和无效 NSTimer 的正确方法?

Since GCD doesn't assure you that a serial queue will always run blocks on the same thread, what's the right way to ensure that you schedule and invalidate an NSTimer on the same thread?

编辑:

根据以下答案的建议,我创建了 MSWeakTimer https://github.com/mindsnacks/MSWeakTimer )这是使用 GCD 可以在任何队列中使用。

Following the advise of the answer below, I created MSWeakTimer (https://github.com/mindsnacks/MSWeakTimer) which is a custom timer implementation using GCD that can be used from any queue.

推荐答案

你不应该安装<$ c在GCD管理的匿名工作线程上$ c> NSTimer 。

在G中使用调度计时器源CD而不是 NSTimer ,c.f。 dispatch_source_create(3)。

Use dispatch timer sources with GCD instead of NSTimer, c.f. dispatch_source_create(3).

NSTimer 依赖于当前线程的runloop,这不是一个有意义的东西GCD队列。有关GCD和runloop API的更多详细信息,请参阅WWDC2012 GCD会话。

NSTimer relies on the current thread's runloop, which is not something that makes sense for a GCD queue. See the WWDC2012 GCD session for more details around GCD and runloop APIs.

这篇关于在GCD串行队列上安排和使NSTimers无效是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆