【发布时间】:2021-05-18 16:57:31
【问题描述】:
我的场景是这样的。我需要发送一个网络请求,作为响应,我将成为一个图像 URL 列表。然后我需要同时发送多个网络请求来获取所有这些图像,一旦我下载了所有图像,我需要填充一个tableView。
为了满足这些要求,我试图了解 Playground 中 DispatchQueue 和 DispatchGroup 之间的关系,到目前为止,这是我的代码。
var concurrentQueue = DispatchQueue(label: "test",attributes: .concurrent)
var myGroup = DispatchGroup()
var mySecondGroup = DispatchGroup()
myGroup.notify(queue: DispatchQueue.main) {
print("Initial Json request with List of URLs completed")
mySecondGroup.enter()
concurrentQueue.async {
for i in 10...15 {
print(i)
if(i==15){
mySecondGroup.leave()
}
}
}
}
mySecondGroup.notify(queue: DispatchQueue.main) {
print("All Images download complete")
}
myGroup.enter()
concurrentQueue.async {
for i in 0...5 {
print(i)
if(i==5){
myGroup.leave()
}
}
}
问题是我得到了结果
0
1
2
3
4
5
Initial Json request with List of URLs completed
10
11
All Images download complete
12
13
14
15
但我想要的是这样的
0
1
2
3
4
5
Initial Json request with List of URLs completed
10
11
12
13
14
15
All Images download complete
我并不真正理解我在这里做错了什么,任何帮助将不胜感激。
【问题讨论】:
-
pastebin.com/U7k32tKs 应该可以工作。
-
它是如何工作的?
-
你需要为每个“离开”匹配一个“进入”,这就是小组如何知道这组任务何时完成。
-
但我想我已经做到了。我们启动 myGroup.enter(),然后是 myGroup.leave(),这反过来触发 myGroup 的 notify 方法,我在其中执行 mySecondGroup.enter(),然后在处理 mySecondGroup.leave() 之后。所以我想我已经将每个“输入”与“离开”匹配了
-
但是,您调用
mySecondGroup.enter()太晚了,它应该已经调用了它的notify()。另外,将 notify 放在最后(至少在自定义enter()之后),否则它也可能被调用得太早。
标签: ios swift multithreading grand-central-dispatch dispatchgroup