问题描述
我用DispatchQueue做了简单测试:
I did the simple test with DispatchQueue:
DispatchQueue.global(qos: .background).sync {
if Thread.isMainThread {
print("Main thread")
}
}
它打印出来:
Main thread
为什么此代码在主线程上执行?应该在后台线程上执行(它已添加到后台队列中),对吧?
Why does this code execute on the main thread? It should be performed on a background thread (it was added to a background queue), right?
推荐答案
因为它没有实际上必须。您正在使用同步功能来阻止主线程。 iOS选择只在主线程上执行它,而不用费心切换到(后台队列的)后台线程,因为这实际上并不重要,因为无论如何主线程都被阻塞了。
Because it doesn't actually have to. You're blocking the main thread by using sync. iOS is choosing to just execute it on the main thread instead of bothering to switch to a background thread (of a background queue) as it doesn't really matter due to main thread being blocked anyways.
有关同步功能的Apple文档(和快速帮助)包括以下行:
Apple's docs (and quickhelp) on the sync function include the line:
这篇关于为什么同步代码块总是在主线程上调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!