Why would anyone ever use dispatch_sync
if the block has to wait until the main thread finishes. What is the benefit of using this function rather than writing code in-line (non-block and outside of Grand Central Dispatch). I may be misunderstanding what dispatch_sync
actually does. Thanks.
dispatch_sync
does what you think — it posts the block to the nominated queue and blocks the current queue until the block has been performed. The main queue/thread isn't specifically involved unless you're either dispatching to it or from it.
So, you'd generally use it if an operation had to be performed on a different queue/thread — such as a SQLite or OpenGL operation — but you either needed the result of the operation or simply needed to know that the operation was complete for functionality terms.
The pattern:
dispatch_async(otherQueue,
^{
id result = doHardTask();
dispatch_async(originalQueue,
^{
didGetResult(result);
});
});
is better practice but isn't really something you can just glue on at the end.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With