bufferoverflow76 bufferoverflow76 - 3 years ago 189
Swift Question

DispatchQueue sync block vs async block

Assume I have the following

DispatchQueue
:

let myqueue = DispatchQueue(label: "myqueue")


What is the difference between
async
block and
sync
block? Can someone explain what it means?

e.g In the main thread, in the middle execution of the main thread. What will it happen if I call
myqueue.async{...}
or
myqueue.sync{...}


e.g

override func viewDidLoad() {
super.viewDidLoad()

myqueue.async{...}

myqueue.sync{...}
}

Answer Source

dispatch_async:

Submits a block for asynchronous execution on a dispatch queue and returns immediately.

dispatch_sync:

Submits a block object for execution on a dispatch queue and waits until that block completes.

dispatch_sync will return after the block is finished meanwhile dispatch_async will return after it is added to the queue and may not be finished.

Example:
You have two tasks, Task1 and Task2.

When you submit a block to run Task1 sync, then Task2 will wait until that is finished before Task2 will run.

When you submit a block to run Task1 async, then Task2 will also run and Task1 can be completed before or after Task2.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download