2

Is it safe to dispatch a block of code with delay on the main thread, if you are already on the main thread?

dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, seconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), theBlock);

Or is there a safer way? Do I have to perform any checks if I am already on main queue (main thread) when executing this?

David H
  • 40,852
  • 12
  • 92
  • 138
openfrog
  • 40,201
  • 65
  • 225
  • 373

2 Answers2

5

You generally don't have to check whether you're already on the main thread if the block is enqueued asynchronously, which dispatch_after does:

This function waits until the specified time and then asynchronously adds block to the specified queue.

You would have to check however, if you were using a synchronous function like dispatch_sync. That would otherwise result in a deadlock.

omz
  • 53,243
  • 5
  • 129
  • 141
  • I'm calling the above code simply from the main thread (after user presses a button). Can you give an example with dispatch_sync that causes a deadlock? – openfrog Jun 28 '13 at 11:44
  • dispatch_get_current_queue is deprecated. – openfrog Jun 28 '13 at 13:24
  • You can use `[NSThread isMainThread]` instead of `dispatch_get_current_queue` (obviously only for the main thread queue). – omz Jun 28 '13 at 17:33
0

Yes, it is safe. There are other ways to perform actions on main thread, but I don't guess they are safer. You can use, for example:

[[NSOperationQueue mainQueue] addOperationWithBlock: YOUR_BLOCK_HERE ];

I really prefer NSOperationQueue when the extra features of GCD are not needed. It is easier.

Gabriel
  • 3,319
  • 1
  • 16
  • 21