Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 657
Javier Soto Avatar asked Feb 01 '13 19:02

Javier Soto


1 Answers

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.

like image 121
das Avatar answered Nov 20 '22 02:11

das