SWIFT - OperationQueue.main.addOperation 和 DispatchQueue.main.async 之间有什么区别?

标签 swift asynchronous queue operation dispatch-queue

有时我必须在主线程上执行某些操作,建议将代码放置在 OperationQueue.main.addOperation 中。

其他时候,建议将代码编写在DispatchQueue.main.async内。

这两者有什么区别?

(有类似的问题标题,但内容不匹配。)

最佳答案

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

OperationQueue 来自 Apple 文档

The NSOperationQueue class regulates the execution of a set of Operation objects. After being added to a queue, an operation remains in that queue until it is explicitly canceled or finishes executing its task. Operations within the queue (but not yet executing) are themselves organized according to priority levels and inter-operation object dependencies and are executed accordingly. An application may create multiple operation queues and submit operations to any of them.

示例:

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 文档

DispatchQueue manages the execution of work items. Each work item submitted to a queue is processed on a pool of threads managed by the system.

示例:

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

关于SWIFT - OperationQueue.main.addOperation 和 DispatchQueue.main.async 之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50972359/

相关文章:

iOS swift : Send action (control event) from subclass of UIImageView

c# - 跨作用域 DbContext 的并发

laravel - 如何在 laravel 5.7 中限制排队验证和密码重置通知电子邮件的速率

ios - 滚动时不会调用 estimatedHeightForRowAt

ios - 如何检测何时关闭 RPSystemBroadcastPickerView?

swift - AVFoundation 播放连续的视频片段

asp.net-mvc-4 - 在 MVC4 中使函数异步时 HttpContext.Current null

javascript - 如何解决递归异步 promise ?

python - 需要刷新 Python 多处理队列

c++ - 使用循环链表遍历队列