[英]Why is dispatchGroup.notify called after only the first task has exited?
Why is dispatchGroup.notify called after only the first task has exited?为什么在第一个任务退出后调用 dispatchGroup.notify ?
In the following code the output is as follows:在以下代码中,输出如下:
1) Did the other thing
**2) Did all the things**
3) Did one thing
4) done waiting
I would expect:我希望:
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")
}
As a side note if I perform this on the main thread it works as expected.作为旁注,如果我在主线程上执行此操作,它会按预期工作。
According to the very minimal Apple docs: https://developer.apple.com/documentation/dispatch/dispatchgroup根据非常小的 Apple 文档: https : //developer.apple.com/documentation/dispatch/dispatchgroup
func notify(queue: DispatchQueue, work: DispatchWorkItem) Schedules a work item to be submitted to a queue when a group of previously submitted block objects have completed. func notify(queue: DispatchQueue, work: DispatchWorkItem) 当一组先前提交的块对象完成时,安排一个工作项提交到队列。
In my example above I called dispatchQueue.notify before I had submitted my blocks to the queue.在上面的示例中,我在将块提交到队列之前调用了dispatchQueue.notify 。 By updating the code as follows, I was able to get the expected behavior.通过如下更新代码,我能够获得预期的行为。
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")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.