为什么只有第一个任务退出后才调用dispatchGroup.notify?
在以下代码中,输出如下:
1) Did the other thing
**2) Did all the things**
3) Did one thing
4) done waiting
我希望:
1) Did the other thing
2) Did one thing
3) done waiting
**4) Did all the things**
DispatchQueue.global().async {
let dispatchGroup = DispatchGroup()
dispatchGroup.notify(queue: DispatchQueue.main) {
print("Did all the things")
}
dispatchGroup.enter()
DispatchQueue.global().asyncAfter(deadline: .now() + 10) {
print("Did one thing")
dispatchGroup.leave()
}
dispatchGroup.enter()
DispatchQueue.global().async {
print("Did the other thing")
dispatchGroup.leave()
}
dispatchGroup.wait()
print("done waiting")
}
请注意,如果我在主线程上执行此操作,它将按预期工作。
答案 0 :(得分:1)
根据极少的Apple文档:https://developer.apple.com/documentation/dispatch/dispatchgroup
func notify(队列:DispatchQueue,工作:DispatchWorkItem) 安排一组先前个已提交的块对象完成后,将工作项目计划提交到队列。
在上面的示例中,我将
DispatchQueue.global().async {
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
DispatchQueue.global().asyncAfter(deadline: .now() + 10) {
print("Did one thing")
dispatchGroup.leave()
}
dispatchGroup.enter()
DispatchQueue.global().async {
print("Did the other thing")
dispatchGroup.leave()
}
dispatchGroup.notify(queue: DispatchQueue.main) {
print("Did all the things")
}
dispatchGroup.wait()
print("done waiting")
}