[英]Combining DispatchGroup and DispatchQueue
我的場景是這樣的。 我需要發送一個網絡請求,作為響應,我將成為一個圖像 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
我真的不明白我在這里做錯了什么,任何幫助將不勝感激。
DispatchQueue
是調度任務的媒介。
DispatchGroup
就像一個計數器。 調用enter
會增加計數器(通常在調用異步任務之前),而leave
減少計數器(通常在完成處理程序內)。 當計數器達到零時,組會通知。
你的場景需要這樣的東西
let concurrentQueue = DispatchQueue(label: "test",attributes: .concurrent)
let group = DispatchGroup()
concurrentQueue.async {
asynchronousAPI.call() { urls in
for url in urls {
group.enter()
asynchronousImageLoad(url) { data in
// process data
group.leave()
}
}
}
}
group.notify(queue: .main) {
print("done")
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.