我正在使用DispatchGroup
执行任务,但在任务完成之前正在调用group.notify
。
我的代码:
let group = DispatchGroup()
let queueImage = DispatchQueue(label: "com.image")
let queueVideo = DispatchQueue(label: "com.video")
queueImage.async(group: group) {
sleep(2)
print("image")
}
queueVideo.async(group: group) {
sleep(3)
print("video")
}
group.notify(queue: .main) {
print("all finished.")
}
日志:
all finish.
image
video
答案 0 :(得分:2)
更新:上面的问题实际上正确运行(正如rmaddy指出的那样!)
我正在保存下面这个错误的答案,以防其他人对DispatchQueue的async(group :)方法行为感到困惑,因为Apple's swift doc on it目前很糟糕。
需要在每次调用async()之前调用组的enter(),然后需要在每个async()块的末尾调用组的leave(),但在中块。它基本上就像一个refcount,当它达到零(没有进入剩余)时,则调用通知块。
let group = DispatchGroup()
let queueImage = DispatchQueue(label: "com.image")
let queueVideo = DispatchQueue(label: "com.video")
group.enter()
queueImage.async(group: group) {
sleep(2)
print("image")
group.leave()
}
group.enter()
queueVideo.async(group: group) {
sleep(3)
print("video")
group.leave()
}
group.notify(queue: .main) {
print("all finished.")
}
答案 1 :(得分:0)
通用答案:(快速5)
let yourDispatchGroup = DispatchGroup()
yourDispatchGroup.enter()
task1FunctionCall {
yourDispatchGroup.leave() //task 1 complete
}
yourDispatchGroup.enter()
task2FunctionCall {
yourDispatchGroup.leave() //task 2 complete
}
.. ..
yourDispatchGroup.enter()
tasknFunctionCall {
yourDispatchGroup.leave() //task n complete
}
dispatchGroup.notify(queue: .main) {
//This is invoked when all the tasks in the group is completed.
}