[英]dispatch_group_notify has been replaced by instance method DispatchGroup.notify(qos:flags:queue:execute:)
[英]Why is dispatchGroup.notify called after only the first task has exited?
為什么在第一個任務退出后調用 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")
}
作為旁注,如果我在主線程上執行此操作,它會按預期工作。
根據非常小的 Apple 文檔: https : //developer.apple.com/documentation/dispatch/dispatchgroup
func notify(queue: DispatchQueue, work: DispatchWorkItem) 當一組先前提交的塊對象完成時,安排一個工作項提交到隊列。
在上面的示例中,我在將塊提交到隊列之前調用了dispatchQueue.notify 。 通過如下更新代碼,我能夠獲得預期的行為。
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.