7

Sometimes I must do something on the main thread and its suggested to place the code inside a OperationQueue.main.addOperation.

Other times, its suggested to write the code inside DispatchQueue.main.async.

What the difference between these two?

(There's a similar question title, but the content is mismatched.)

2 Answers2

5

I used 'DispatchQueue.main.async' when I perform any task in main thread like Update my APP UI . When you need to run a further operation or block in main thread you can use 'OperationQueue'. Check this article to know more about OperationQueue

OperationQueue From Apple Doc

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.

Example :

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 From Apple Doc

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.

Example :

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()
Nahid Raihan
  • 807
  • 1
  • 9
  • 19
1

OperationQueue is just an objective C wrapper over Grand Central Dispatch (GCD / libdispatch).

If you are using OperationQueue, then you are implicitly using Grand Central Dispatch.

OperationQueue.main.addOperation therefore is using DispatchQueue.main.async under the hood. There is some overhead of using Objective C (OperationQueue) over a C API (GCD) so there is a slight performance gain for using GCD.

I recommend reading Brad Larson's answer on why he prefers GCD over OperationQueue but it is a debatable subject.

NSOperation vs Grand Central Dispatch.