Sebastian Boldt Sebastian Boldt - 2 months ago 17
Swift Question

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 a advantage in performance or something like that?

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);
}
}

Answer

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.