Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the benefit of using dispatch_sync if it has to wait until the main thread completes?

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.

like image 239
Ryan Avatar asked Feb 27 '12 19:02

Ryan


1 Answers

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.

like image 113
Tommy Avatar answered Nov 22 '22 05:11

Tommy