To run tasks on a dispatch queue, use the sync
, async
, and after
methods.
To dispatch a task to a queue asynchronously:
let queue = DispatchQueue(label: "myQueueName")
queue.async {
//do something
DispatchQueue.main.async {
//this will be called in main thread
//any UI updates should be placed here
}
}
// ... code here will execute immediately, before the task finished
To dispatch a task to a queue synchronously:
queue.sync {
// Do some task
}
// ... code here will not execute until the task is finished
To dispatch a task to a queue after a certain number of seconds:
queue.asyncAfter(deadline: .now() + 3) {
//this will be executed in a background-thread after 3 seconds
}
// ... code here will execute immediately, before the task finished
NOTE: Any updates of the user-interface should be called on the main thread! Make sure, that you put the code for UI updates inside
DispatchQueue.main.async { ... }
Types of queue:
let mainQueue = dispatch_get_main_queue()
let highQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)
let backgroundQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)
To dispatch a task to a queue asynchronously:
dispatch_async(queue) {
// Your code run run asynchronously. Code is queued and executed
// at some point in the future.
}
// Code after the async block will execute immediately
To dispatch a task to a queue synchronously:
dispatch_sync(queue) {
// Your sync code
}
// Code after the sync block will wait until the sync task finished
To dispatch a task to after a time interval (use NSEC_PER_SEC
to convert seconds to nanoseconds):
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(2.5 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) {
// Code to be performed in 2.5 seconds here
}
To execute a task asynchronously and than update the UI:
dispatch_async(queue) {
// Your time consuming code here
dispatch_async(dispatch_get_main_queue()) {
// Update the UI code
}
}
NOTE: Any updates of the user-interface should be called on the main thread! Make sure, that you put the code for UI updates inside
dispatch_async(dispatch_get_main_queue()) { ... }