I have been using DispatchQueue.main.async
for a long time to perform UI related operations.
Swift provides both DispatchQueue.main.async
and DispatchQueue.main.sync
, and both are performed on the main queue.
Can anyone tell me the difference between them? When should I use each?
DispatchQueue.main.async {
self.imageView.image = imageView
self.lbltitle.text = ""
}
DispatchQueue.main.sync {
self.imageView.image = imageView
self.lbltitle.text = ""
}
When you use async
it lets the calling queue move on without waiting until the dispatched block is executed. On the contrary sync
will make the calling queue stop and wait until the work you've dispatched in the block is done. Therefore sync
is subject to lead to deadlocks. Try running DispatchQueue.main.sync
from the main queue and the app will freeze because the calling queue will wait until the dispatched block is over but it won't be even able to start (because the queue is stopped and waiting)
When to use sync
? When you need to wait for something done on a DIFFERENT queue and only then continue working on your current queue
Example of using sync:
On a serial queue you could use sync
as a mutex in order to make sure that only one thread is able to perform the protected piece of code at the same time.