openfrog
openfrog

Reputation: 40735

How to safely dispatch code after delay on the main thread, using GCD?

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?

Upvotes: 2

Views: 3343

Answers (2)

omz
omz

Reputation: 53551

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.

Upvotes: 5

Gabriel
Gabriel

Reputation: 3359

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.

Upvotes: 0

Related Questions