gpt4 book ai didi

ios - 为什么只有第一个任务退出后才调用dispatchGroup.notify?

转载 作者:行者123 更新时间:2023-12-02 02:34:44 26 4
gpt4 key购买 nike

为什么只有第一个任务退出后才调用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")

}
<小时/>

作为旁注,如果我在主线程上执行此操作,它会按预期工作。

最佳答案

根据最简单的苹果文档: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.

在上面的示例中,我在将 block 提交到队列之前调用了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")

}

关于ios - 为什么只有第一个任务退出后才调用dispatchGroup.notify?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52204560/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com