Is it safe to schedule and invalidate NSTimers on a GCD serial queue?

牧云@^-^@ 提交于 2019-12-03 17:50:02

问题


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

Special Considerations

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.

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?

EDIT:

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.


回答1:


You should not install an NSTimer on an anonymous worker thread managed by GCD.

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

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.



来源:https://stackoverflow.com/questions/14653951/is-it-safe-to-schedule-and-invalidate-nstimers-on-a-gcd-serial-queue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!