ios 如何限制在任务组中执行的并发任务数

xuo3flqw  于 2022-12-05  发布在  iOS
关注(0)|答案(1)|浏览(150)

下面的函数将下载传递到函数中的资产的图像数据,使用Swift的async/await中的任务组异步和并发地将PHAsset数组转换为Data数组。
当提供100个PHAsset时,所有的任务都会被立即添加到组中,因此100个数据下载请求会同时启动。至少在测试中--据我所知,系统可以决定如何限制它。
如何限制组中同时执行的并发任务的数量?例如,在此场景中,我可能希望一次最多只允许下载10张照片,而不是提供的全部100张(或1000张)。

func loadImageData(for assets: [PHAsset]) {
    Task {
        do {
            let imagesData = try await withThrowingTaskGroup(of: (id: String, data: Data).self) { group in
                for asset in assets {
                    group.addTask {
                        return (id: asset.localIdentifier, data: try await self.imageData(for: asset))
                    }
                }
                
                var dictionary = [String: Data]()
                for try await item in group {
                    dictionary[item.id] = item.data

                    print("Downloaded \(dictionary.count) of \(assets.count)")
                }
                
                return assets.compactMap { dictionary[$0.localIdentifier] }
            }
            
            print("Done")
        } catch {
            print(error)
        }
    }
}

func imageData(for asset: PHAsset) async throws -> Data() {
    //code here makes PHImageManager.requestImageDataAndOrientation play nicely with async/await
}
nx7onnlm

nx7onnlm1#

我不认为有办法限制它的TaskGroup。但对于我的CLI应用程序,我需要限制同时执行的任务的数量,所以当应用程序在后台运行时,我仍然可以与我的mac一起工作。所以我写pool drainer
用法:

let pool = AsyncOperationsPool<Int>(maxConcurrentOperationCount: 5)
for i in 0..<1024 {
    pool.add { /* some heavy async task */ }
}

for try await i in pool {
  // process result
}

相关问题