【问题标题】:How to constrain concurrency (like `maxConcurrentOperationCount`) with Swift Concurrency?如何使用 Swift Concurrency 约束并发(如 `maxConcurrentOperationCount`)?
【发布时间】: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


    【解决方案1】:

    达到一定计数后,可以在循环内插入group.next()调用,例如:

    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)
    
                if i >= 6 {                                                     // max of six at a time
                    try await group.next()
                }
    
                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()
        }
    }
    

    这导致一次不超过六个:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多