为什么从哪里调用 DispatchQueue.main.async 很重要?
Why does it matter from where you call DispatchQueue.main.async?
我写了下面几段代码:
DispatchQueue.main.async {
self.cameraManager.checkForCameraAuthorization(deniedCallback: {
self.presentDeniedAlert()
self.activityIndicator.stopAnimating()
}) {
self.cameraAccess = true
self.cameraButton.isEnabled = false
self.activityIndicator.stopAnimating()
}
}
和
cameraManager.checkForMicrophoneAuthorization(deniedCallback: {
self.presentDeniedAlert()
self.activityIndicator.stopAnimating()
}) {
DispatchQueue.main.async {
self.microphoneAccess = true
self.microphoneButton.isEnabled = false
self.activityIndicator.stopAnimating()
}
}
}
(区别在于调用async的地方)
1.崩溃self.cameraButton.isEnabled = false can only be called from main thread
2.一个完成就好了。
谁能解释一下,为什么会这样?
差异如下所述。
在 1st 代码中,您的 checkForCameraAuthorization
回调在不同的线程中执行,您应该知道 UIApplication/UI 相关任务应该在主线程中执行.
在 2nd 代码中,在 checkForCameraAuthorization
中获得回调后,您正在主线程中执行 UI 相关任务,因此它工作正常。
如有疑问请评论。
调度队列是线程安全的,这意味着您可以同时从多个线程访问它们。始终更新主队列中的 UI 个元素。
在第一个代码中,您在不同的线程上更新 UI,而不是从主线程。
如需更多参考资料,您可以关注这些 link -
https://www.quora.com/Why-must-the-UI-always-be-updated-on-Main-Thread#
https://www.raywenderlich.com/5370-grand-central-dispatch-tutorial-for-swift-4-part-1-2
我写了下面几段代码:
DispatchQueue.main.async {
self.cameraManager.checkForCameraAuthorization(deniedCallback: {
self.presentDeniedAlert()
self.activityIndicator.stopAnimating()
}) {
self.cameraAccess = true
self.cameraButton.isEnabled = false
self.activityIndicator.stopAnimating()
}
}
和
cameraManager.checkForMicrophoneAuthorization(deniedCallback: {
self.presentDeniedAlert()
self.activityIndicator.stopAnimating()
}) {
DispatchQueue.main.async {
self.microphoneAccess = true
self.microphoneButton.isEnabled = false
self.activityIndicator.stopAnimating()
}
}
}
(区别在于调用async的地方)
1.崩溃self.cameraButton.isEnabled = false can only be called from main thread
2.一个完成就好了。
谁能解释一下,为什么会这样?
差异如下所述。
在 1st 代码中,您的 checkForCameraAuthorization
回调在不同的线程中执行,您应该知道 UIApplication/UI 相关任务应该在主线程中执行.
在 2nd 代码中,在 checkForCameraAuthorization
中获得回调后,您正在主线程中执行 UI 相关任务,因此它工作正常。
如有疑问请评论。
调度队列是线程安全的,这意味着您可以同时从多个线程访问它们。始终更新主队列中的 UI 个元素。
在第一个代码中,您在不同的线程上更新 UI,而不是从主线程。
如需更多参考资料,您可以关注这些 link -
https://www.quora.com/Why-must-the-UI-always-be-updated-on-Main-Thread#
https://www.raywenderlich.com/5370-grand-central-dispatch-tutorial-for-swift-4-part-1-2