【问题标题】:Combining DispatchGroup and DispatchQueue结合 DispatchGroup 和 DispatchQueue
【发布时间】:2021-05-18 16:57:31
【问题描述】:

我的场景是这样的。我需要发送一个网络请求,作为响应,我将成为一个图像 URL 列表。然后我需要同时发送多个网络请求来获取所有这些图像,一旦我下载了所有图像,我需要填充一个tableView

为了满足这些要求,我试图了解 Playground 中 DispatchQueueDispatchGroup 之间的关系,到目前为止,这是我的代码。

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


【解决方案1】:

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")
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多