在 Grand Central Dispatch(GCD) 佇列中執行任務
Version = 3.0
要在排程佇列上執行任務,請使用 sync
,async
和 after
方法。
要以非同步方式將任務分派到佇列:
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
要同步將任務分派到佇列:
queue.sync {
// Do some task
}
// ... code here will not execute until the task is finished
要在一定秒數後將任務分派到佇列:
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
注意: 應在主執行緒上呼叫使用者介面的任何更新! 確保你將使用者更新的程式碼放在
DispatchQueue.main.async { ... }
中
Version = 2.0
佇列型別:
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)
要以非同步方式將任務分派到佇列:
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
要同步將任務分派到佇列:
dispatch_sync(queue) {
// Your sync code
}
// Code after the sync block will wait until the sync task finished
要在一段時間間隔後排程任務(使用 NSEC_PER_SEC
將秒轉換為納秒):
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
}
要非同步執行任務而不是更新 UI:
dispatch_async(queue) {
// Your time consuming code here
dispatch_async(dispatch_get_main_queue()) {
// Update the UI code
}
}
注意: 應在主執行緒上呼叫使用者介面的任何更新! 確保你將使用者介面更新的程式碼放在
dispatch_async(
dispatch_get_main_queue()) { ... }
中