I found some code example recently
func stpDispatchToMainThreadIfNecessary(_ block: @escaping () -> Void) {
if Thread.isMainThread {
block()
} else {
DispatchQueue.main.async(execute: block)
}
}
It looks like if we will wrap all blocks inside DispatchQueue.main.async no matter which thread it is it will technically work.
The question is why check for the main thread?
Does it add some optimization? If yes - where to read about it and how to benchmark it?
The important bit if the async
dispatch.
If stpDispatchToMainThreadIfNecessary
is called from the main thread, block
is executed synchronously, while if the func is called from a background thread, due to the async(execute:)
call, block
is executed asynchronously.
This means that when called from the main thread, due to the sync execution, block
will be executed sooner than if it was also wrapped in a Dispatch async call.
You could change the async(execute:)
to sync(execute:)
, which in case of the main thread would result in no delay compared to simply calling block()
, however, you should not be dispatching synchronously to the main thread from a background thread, because that might freeze the UI.
So checking whether the func was called from the main thread and in this case synchronously executing block
, while asynchronously dispatching it to the main thread from any other thread ensures that there is no unnecessary blocking of the main thread when calling the func from another thread, but also no unnecessary delay when calling the func from the main thread.