Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SWIFT - What's the difference between OperationQueue.main.addOperation and DispatchQueue.main.async?

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

like image 301
Yuma Technical Inc. Avatar asked Jun 21 '18 15:06

Yuma Technical Inc.


People also ask

What is the difference between DispatchQueue main async and DispatchQueue main sync?

Synchronous function returns control to the current queue only after the task is finished. It blocks the queue and waits until the task is finished. Asynchronous function returns control to the current queue right after task has been sent to be performed on the different queue.

Why use DispatchQueue main async in Swift?

To summarize, DispatchQueue. async allows you to schedule work to be done using a closure without blocking anything that's ongoing. In most cases where you need to dispatch to a dispatch queue you'll want to use async .

What is DispatchQueue Main?

DispatchQueue. main is the dispatch queue associated with the main thread of the current process. The system is responsible for generating this queue which represents the main thread. A dispatch queue executes tasks serially or concurrently on its associated thread.

Is DispatchQueue main concurrent?

In general, dispatch queues will only perform one task at a time in a first-in, first-out kind of fashion. They can, however, be configured to schedule work concurrently. The main dispatch queue is a queue that runs one task at a time.


1 Answers

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()
like image 182
Nahid Raihan Avatar answered Sep 20 '22 17:09

Nahid Raihan