Dispatch
Dispatch (Grand Central Dispatch) is a framework for running code on different threads. By default, all code on iOS is run on the main thread (also known as the UI thread).
In new code, prefer Swift concurrency — async/await, Task, and @MainActor — over Dispatch. Dispatch remains common in existing codebases and interoperates with Swift concurrency.
- Run code on a background thread
- Run code on the main thread from a background thread
- Run code in the main thread after a delay
- Practical example
- See also
- Further reading
- Notes
Run code on a background thread
Time-intensive work can run on a background thread.1
import Foundation
// Code in the main thread
DispatchQueue.global(qos: .background).async {
// Some code that takes a long time to execute
}
Run code on the main thread from a background thread
When background thread work done, the UI can be updated on the main thread.2
import Foundation
// Code in the main thread
DispatchQueue.global(qos: .background).async {
// Some code that takes a long time to execute
DispatchQueue.main.async {
// More code in the main thread
}
}
Run code in the main thread after a delay
With asyncAfter it is possible to tell the Dispatch framework to execute a block of code after a delay (the Swift concurrency equivalent is try await Task.sleep(for: .seconds(3))):
import Foundation
// Code in the main thread
DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
// Code in the main thread that runs after 3 seconds
}
Practical example
import Foundation
@objc func didTapOnGenerateImageButton() {
DispatchQueue.global(qos: .background).async {
let newImage = ImageManager.generateImage() // This synchronous method could take a long time
DispatchQueue.main.async {
self.imageView = newImage // The UI can only be updated on the main thread
}
}
}