Wednesday 24 June 2015

dispatch_async vs dispatch_sync

dispatch_async means "put this block on the queue immediately return." dispatch_sync means "put this block on the queue, wait for it to run, and then return.


The difference between dispatch_sync and dispatch_async is simple.
In both of your examples, TASK 1 will always execute before TASK 2 because it was dispatched before it.

In the dispatch_sync example, however, you won't dispatch TASK 2 until after TASK 1 has been dispatched and executed. This is called "blocking". Your code waits (or "blocks") until the task executes.


In the dispatch_async example, your code will not wait for execution to complete. Both blocks will dispatch (and be enqueued) to the queue and the rest of your code will continue executing on that thread. Then at some point in the future, (depending on what else has been dispatched to your queue), Task 1 will execute and then Task 2 will execute.


dispatch_sync:

Here one example for dispatch_sync with NSUrlSession:


 let dataTask:NSURLSessionDataTask = sharedSession.dataTaskWithURL(NSURL(string: kurl)!, completionHandler:
            {
                (data:NSData!,response, error: NSError!) -> Void in
                
                if error != nil
                            {println("demo3")
                                 println(error?.localizedDescription)
                            }
                
                            dispatch_sync(diffQueue)
                                {
                                    var error:NSError?
                
                                    let weatherDictionary=NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary
                
                                    if (error != nil)
                                    {
                                        println("demo1")
                                        println(error?.localizedDescription)
                                                           }
                                    else
                                    {
                                        println(
                                        "weatherDictionary = \(weatherDictionary)")
                
                                    }
                
                }
                 })
             dataTask.resume()


dispatch_async

 let dataTask:NSURLSessionDataTask = sharedSession.dataTaskWithURL(NSURL(string: kurl)!, completionHandler:
            {
                (data:NSData!,response, error: NSError!) -> Void in
                
                if error != nil
                            {println("demo3")
                                 println(error?.localizedDescription)
                            }
                
                            dispatch_sync(diffQueue)
                                {
                                    var error:NSError?
                
                                    let weatherDictionary=NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary
                
                                    if (error != nil)
                                    {
                                        println("demo1")
                                        println(error?.localizedDescription)
                                                           }
                                    else
                                    {
                                        println(
                                        "weatherDictionary = \(weatherDictionary)")
                
                                    }
                
                }
                 })
             dataTask.resume()

1 comment:

  1. worst explanation ever.

    you did not even bother to _change_ the `dispatch_sync` to `dispatch_async` in the second snippet, not mentioning that the initial 'explanation' (or what) states the obvious only and gives no reason or explanation of _why_ we should use this or that.

    ReplyDelete