DispatchQueue.main.async 和 DispatchQueue.main.sync 的区别 [英] Difference between DispatchQueue.main.async and DispatchQueue.main.sync
问题描述
我长期使用DispatchQueue.main.async
来进行UI相关的操作.
I have been using DispatchQueue.main.async
for a long time to perform UI related operations.
Swift 提供了 DispatchQueue.main.async
和 DispatchQueue.main.sync
,并且都在主队列上执行.
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 = ""
}
推荐答案
当您使用 async
时,它可以让调用队列继续前进,而无需等待分派块执行.相反 sync
将使调用队列停止并等待您在块中分派的工作完成.因此sync
容易导致死锁.尝试从主队列运行 DispatchQueue.main.sync
,应用程序将冻结,因为调用队列将等待调度块结束,但它甚至无法启动(因为队列是停下来等待)
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)
何时使用sync
?当您需要等待在 DIFFERENT 队列上完成某事,然后才继续处理当前队列时
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
使用同步的例子:
在串行队列上,您可以使用 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.
这篇关于DispatchQueue.main.async 和 DispatchQueue.main.sync 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!