问题
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