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.)
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.
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 .
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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With