【问题标题】:SWIFT - What's the difference between OperationQueue.main.addOperation and DispatchQueue.main.async?SWIFT - OperationQueue.main.addOperation 和 DispatchQueue.main.async 有什么区别?
【发布时间】:2018-12-01 00:17:19
【问题描述】:

有时我必须在主线程上做点什么,建议将代码放在OperationQueue.main.addOperation 中。

其他时候建议在DispatchQueue.main.async里面写代码。

这两者有什么区别?

(有类似题名,但内容不匹配。)

【问题讨论】:

标签: swift asynchronous queue operation dispatch-queue


【解决方案1】:

当我在主线程中执行任何任务(例如 Update my APP UI )时,我使用了“DispatchQueue.main.async”。当您需要在主线程中运行进一步的操作或阻塞时,您可以使用“OperationQueue”。查看这篇文章以了解更多关于OperationQueue

OperationQueue 来自 Apple Doc

NSOperationQueue 类管理一组 操作对象。加入队列后,还有一个操作 在该队列中,直到它被显式取消或完成执行 它的任务。队列中的操作(但尚未执行)是 它们按照优先级和互操作进行组织 对象依赖关系并相应地执行。一个应用程序可以 创建多个操作队列并向其中任何一个提交操作。

例子:

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var activityIndicator: UIActivityIndicatorView!

    override func viewDidLoad() {
        super.viewDidLoad()
        activityIndicator.startAnimating()
        calculate()
    }

    private func calculate() {
        let queue = OperationQueue()
        let blockOperation = BlockOperation {

            var result = 0

            for i in 1...1000000000 {
                result += i
            }

            OperationQueue.main.addOperation {
                self.activityIndicator.stopAnimating()
                self.label.text = "\(result)"
                self.label.isHidden = false
            }
        }

        queue.addOperation(blockOperation)
    }

}

DispatchQueue 来自 Apple Doc

DispatchQueue 管理工作项的执行。每个工作项 提交到队列的线程池由 系统。

例子:

URLSession.shared.dataTask(with: url) { data, response, error in
    guard let data = data, error == nil else { 
        print(error ?? "Unknown error")
        return 
    }

    do {
        let heroes = try JSONDecoder().decode([HeroStats].self, from: data)
        DispatchQueue.main.async {
            self.heroes = heroes
            completed()
        }
    } catch let error {
        print(error)
    }
}.resume()

【讨论】:

    【解决方案2】:

    OperationQueue 只是 Grand Central Dispatch (GCD / libdispatch) 的客观 C 包装器。

    如果您使用的是 OperationQueue,那么您就是在隐式使用 Grand Central Dispatch。

    OperationQueue.main.addOperation 因此在后台使用 DispatchQueue.main.async。与 C API (GCD) 相比,使用 Objective C (OperationQueue) 会产生一些开销,因此使用 GCD 会略微提高性能。

    我建议阅读 Brad Larson 关于为什么他更喜欢 GCD 而不是 OperationQueue 的回答,但这是一个值得商榷的话题。

    NSOperation vs Grand Central Dispatch.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-03
      • 2020-10-14
      • 1970-01-01
      • 2017-03-03
      • 2018-03-21
      • 2015-02-10
      • 2017-09-04
      相关资源
      最近更新 更多