【发布时间】:2022-02-18 06:06:09
【问题描述】:
我正在尝试执行一系列网络请求,并希望在新的 Swift 并发系统中限制并发任务的数量。对于操作队列,我们将使用maxConcurrentOperationCount。在合并中,flatMap(maxPublishers:_:)。新的 Swift 并发系统中的等价物是什么?
例如,它不是非常相关,但请考虑:
func download() async throws {
try await withThrowingTaskGroup(of: Void.self) { group in
for i in 0..<20 {
let source = sourceUrl(for: i)
let destination = destinationUrl(for: i)
group.addTask {
let (url, _) = try await self.session.download(from: source)
try? FileManager.default.removeItem(at: destination)
try FileManager.default.moveItem(at: url, to: destination)
}
}
try await group.waitForAll()
}
}
这导致所有请求同时运行:
URLSession 不尊重httpMaximumConnectionsPerHost 的事实很有趣,但不是这里的突出问题。更一般地说,我正在寻找如何限制并行运行的一系列异步任务的并发程度。
【问题讨论】:
标签: swift async-await