Home > DeveloperSection > Forums > How to use dispatch_async, dispatch_sync in Objective-C?
Chintoo Semi

Total Post:135

Points:947
Posted on    January-13-2016 12:36 AM

 iPhone iPhone  Ios  Objective C 
Ratings:


 1 Reply(s)
 674  View(s)
Rate this:

I have a need to create serial queue in our iPhone app. I use dispatch_queue_t in our code like this:

dispatch_queue_t MyQueue = dispatch_queue_create("My Queue", DISPATCH_QUEUE_SERIAL);

But I want to know the difference between dispatch_sync and dispatch_async.
Can anyone explain me both differences? and which will be the best to use in our code.
Thank you.



Tarun Kumar

Total Post:210

Points:1614
Posted on    February-20-2016 5:59 AM

If you want to execute any specific task before any specific operation then use it between the dispatch_sync block. The code written in the dispatch_sync block will execute first because dispatch_sync() function creates a simple deadlock, as the currently executing block will waits for the next block to complete but the next block will not start until the currently running block completes.
and the dispatch_async block will execute with default queue of your application main queue for example if we are downloading a file form the network and want to display updating in progress bar of downloads.
Example of dispatch_async() function:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void)
{
    // this is the background thread
    dispatch_async(dispatch_get_main_queue(), ^(void){
        // here you can display the updates of the progress bar
    });
});
I hope the the above explanation is sufficient.

Don't want to miss updates? Please click the below button!

Follow MindStick