使 Swift Grand Central Dispatch 更容易使用
Sprint 包含 3 种类型
Sprint
:一个 dispatch_block_t
包装器SprintQueue
:一个 dispatch_queue_t
包装器SprintGroup
:一个 dispatch_group_t
包装器SprintQueue
是一个枚举,其值与它在上面运行的 Quality of Service 类(QoS)相关
主
用户交互
用户启动
实用程序
后台
您也可以有一个自定义队列,可以是串行或并发
自定义(dispatch_queue_t
)
let backgroundQueue: SprintQueue = .Background
backgroundQueue.async {
// background work
}.finished {
// background work is finished
// this block will be run on the same thread as async
}.finished(.Main) {
// this finish block will be run on the Main thread
// finish can be chained as many times as you want
}
还有一个 sync
方法可以同步运行。
SprintQueue
有一个 after
方法来在设定时间后运行一个块
let queue: SprintQueue = .Main
queue.after(5.0) {
print("test")
}
// test will print after 5 seconds
循环可以通过 apply
方法进行并行化
let dataToCompute: [SomeObject] = dataArray
var computedData = []
let queue: SprintQueue = .UserInitiated
queue.apply(dataToCompute.count) {
index in
let computedDatum = dataToCompute[index].computeData()
computedData.apped(computedDatum)
}
每个方法返回一个 Sprint
,可以取消它(假设它还没有开始)
let sprint = SprintQueue.Background.async {
// update cache
}
// the operation is cancelled, if it has not been started
sprint.cancel()
除了苹果给出的五个内置 QoS 类,您还可以通过两个静态方法创建一个自定义队列,可以是串行或并发:
// a custom concurrent queue
let concurrentQueue = SprintQueue.customConcurrent(label: "com.example.concurrent")
// A custom serial queue
let serialQueue = SprintQueue.customSerial(label: "com.example.concurrent")
屏障操作就像 async
和 sync
一样编写
let customConcurrentQueue = SprintQueue.customConcurrent(label: "com.example.barrierExample")
customConcurrentQueue.async {
// stuff A
}
customConcurrentQueue.barrierAsync {
// stuff B
// (something that could result in a race if not ran in a barrier)
}
customConcurrentQueue.async {
// stuff C
}
// stuff B is guarenteed to happen after A is completed finished and stuff C will not happen until B is completely finished
您还可以创建用于管理多个异步操作的调度组。
每个 SprintGroup
都有一个内置的 async
方法,用于处理该操作的进入和退出组
let group = SprintGroup()
group.async(.Background) {
// stuff 1
}
group.async(.UserInteractive) {
// stuff 2
}
group.finished {
// stuff 1 + 2 have finished running
// functions exactly the same as Sprint.finished() with an optional SprintQueue parameter
}
组也有一个 wait
方法
group.async {
// stuff
}
group.async {
// more stuff
}
if group.wait(10.0) {
// the stuff finished in 10.0 seconds
} else {
// the stuff did NOT finish in 10.0 seconds and the wait timed out
}
如果您想手动管理与 SprintGroup 相关的块,也可以手动进入和退出
group.enter()
youownapi.call {
// stuff
other.call {
// more stuff
callback.hell {
// even more stuff
group.leave()
}
}
}
group.wait(10.0)
// won't be executed until callback.hell is run or 10.0 seconds pass
print("done waiting")
感谢查看这些信息 :)
请这样做!我很乐意听您的想法和意见。