【问题标题】:Why does it matter from where you call DispatchQueue.main.async?为什么从哪里调用 DispatchQueue.main.async 很重要?
【发布时间】:2019-02-20 09:56:44
【问题描述】:

我写了以下代码:

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()
        }
    }
}

(区别在于调用异步的地方)

1.崩溃self.cameraButton.isEnabled = false can only be called from main thread

2.一个完成就好了。

谁能解释一下,为什么会这样?

【问题讨论】:

    标签: ios swift grand-central-dispatch dispatch-queue


    【解决方案1】:

    差异如下所述。

    1st 代码中,您的 checkForCameraAuthorization 回调在不同的线程中执行,您应该知道 UIApplication/UI 相关的任务应该在主线程中执行。

    在获得checkForCameraAuthorization 回调后的2nd代码中,您正在主线程中执行与UI相关的任务,因此它可以正常工作。

    如有疑问请评论。

    【讨论】:

    • 所以从.main.async调用函数不就是在这个线程中调用了回调吗?例如。回调仍然没有从 .main.async 调用,对吧?
    • 是的,您将整个任务提交到主队列中,但这并不意味着回调也会发生在主队列中。
    【解决方案2】:

    调度队列是线程安全的,这意味着您可以同时从多个线程访问它们。始终从主队列更新 UI 元素。

    在第一个代码中,您正在更新不同线程上的 UI,而不是来自主线程。

    更多参考,您可以点击这些链接-

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-26
      • 2013-10-10
      • 2013-03-19
      相关资源
      最近更新 更多