HOW TO USE DISPATCH_ASYNC, DISPATCH_SYNC IN OBJECTIVE-C?

Chintoo Semi

Total Post:135

Points:947
Posted by  Chintoo Semi
 1322  View(s)
Ratings:
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.

  1. Tarun Kumar

    Post:214

    Points:1642
    Re: How to use dispatch_async, dispatch_sync in Objective-C?

    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.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!