简体   繁体   中英

Why does dispatchQueue.main give me the option of sync or async if main queue is always sync

Why does dispatchQueue.main give me the option of sync or async if main queue is always sync

dispatchQueue.main.async{
    //code
}

dispatchQueue.main.async{
    //code
}

Is the same as

dispatchQueue.main.sync{
    //code
}

dispatchQueue.main.sync{
    //code
}

So I was wondering if there is any difference

The main queue is no different than any other queue with regard to whether you can enqueue something to it synchronously or asynchronously.

The only rule you must adhere to is to never use sync to enqueue something onto the same queue currently being used. That will cause a deadlock. Again, this is true no matter the queue, main or otherwise.

To answer your question "Is the same as" - no, it is not the same. Assuming both sets of code are being called from some background queue, in the first set of code, the background queue will keep on moving along without regard to when the two blocks eventually get executed on the main queue. In the second set of code (using sync ), the background queue blocks each time until each block of code is run on the main queue.

If both sets of code are being called from the main queue, then there is a bigger difference. The first set of code (with async ) keeps working. The second set of code (with sync ) will cause the main queue to block at the first call to sync and your app will become unresponsive until the user (or the OS) kills it.

The only possibly relevant difference between the main queue and other queues is that the main queue is always a serial queue while background queues can be either serial or concurrent. But both have valid uses for using sync or async as long as you avoid using sync where both queues are the same.

Async : Non blocking, gets scheduled somewhere in the near future on that specific queue.

Sync : Gets executed right away on that specific queue.

What you are talking about is the situation where you are executing code on the main thread and dispatching something asynchronous or synchronous on that same queue. For async this is no problem as that block gets scheduled somewhere in the near future when there is a timeslot available on that queue. However a sync block which is executed on the same queue as its called upon has the possibility to deadlock.

This does not only hold for the main queue but also for any other queue, so if you are dispatching synchronously to a queue, make sure that thats another queue then the queue you are currently working on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM