Sebastian Boldt
Sebastian Boldt

Reputation: 5321

Is it necessary to check whether the current thread is the main thread or not before dispatching to it asynchronously?

Is it really necessary to check whether the current thread is the main thread or not before dispatching to it asynchronously? Is there any advantage in performance or something else?

I know that dispatching synchronously from the same queue results in a deadlock. But do I really need to check the current Thread like someone did in the following Snippet?

+ (void)dispatchOnMainThread:(void (^)(void))task
    {
        if ([NSThread isMainThread]) // Is this necessary?
        {
            task();
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), task);
        }
    }

Upvotes: 4

Views: 462

Answers (2)

gnasher729
gnasher729

Reputation: 52538

You don't need to check whether you are on the main thread, dispatch_async just puts the task into a queue and returns. Perfectly safe.

On the other hand, if you check whether you are on the main thread and execute the task directly, then don't call your method dispatchOnMainThread, because it doesn't dispatch. Application behaviour can change because of this. I'd call it runOnMainThread, and I'd make it a plain C function. And it's nicer for debugging.

Upvotes: 0

matt
matt

Reputation: 535138

But do i really need to check the current Thread like someone did in the following Snippet

Not really. If you're already on the main thread, then when your code comes to an end, your dispatch_async block will be dispatched. So there might be a slight delay because we need the current run loop / transaction to come to an end, but it won't be noticeable.

I use dispatch_async to the main thread all the time as a way of making sure I'm on the main thread in situations where I'm uncertain (KVO callbacks, for example). No harm, no foul. It's just a form of insurance.

Upvotes: 5

Related Questions