示例工程 20-async-await-structured-concurrency
20-async-await-structured-concurrency/Sources/Ch20Kit/Fetching.swift
/// 用本地延迟模拟 I/O:不联网、不依赖外部服务。
public struct SimulatedDownloader: Sendable {
public let delay: Duration
public init(delay: Duration = .milliseconds(20)) {
self.delay = delay
}
public func fetch(_ id: Int) async -> String {
try? await Task.sleep(for: delay)
return "item-\(id)"
}
}
public enum Fetching {
/// 串行:前一个完成后才开始下一个。
public static func serial(_ ids: [Int], downloader: SimulatedDownloader = .init()) async
-> [String]
{
var results: [String] = []
for id in ids {
results.append(await downloader.fetch(id))
}
return results
}
/// 并发:任务组里同时启动,完成顺序不保证。
public static func concurrent(_ ids: [Int], downloader: SimulatedDownloader = .init()) async
-> [String]
{
await withTaskGroup(of: String.self) { group in
for id in ids {
group.addTask {
await downloader.fetch(id)
}
}
var results: [String] = []
for await result in group {
results.append(result)
}
return results
}
}
/// `async let`:固定数量的并发子任务,父任务等待全部完成。
public static func pair(downloader: SimulatedDownloader = .init()) async -> [String] {
async let first = downloader.fetch(1)
async let second = downloader.fetch(2)
return await [first, second]
}
}
/// 取消是协作式的:任务要自己检查 `Task.isCancelled`。
public enum CancellationLab {
public static func countUntilCancelled(limit: Int) async -> Int {
var count = 0
for _ in 0..<limit {
if Task.isCancelled { break }
try? await Task.sleep(for: .milliseconds(5))
count += 1
}
return count
}
public static func add(_ lhs: Int, _ rhs: Int) async -> Int {
lhs + rhs
}
}