在 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()) { ... }
中