示例工程 20-async-await-structured-concurrency

20-async-await-structured-concurrency/Sources/Ch20Demo/App.swift

swift · 1.1 KB

import Ch20Kit
import Foundation
 
@main
struct Ch20Demo {
    static func main() async {
        let ids = [1, 2, 3, 4]
        let serial = await Fetching.serial(ids)
        print("[20.1] 串行结果 = \(serial.sorted())")
 
        let concurrent = await Fetching.concurrent(ids)
        print("[20.2] 并发结果 = \(concurrent.sorted())")
        print("[20.2] 完成顺序不保证,排序后才稳定")
 
        let pair = await Fetching.pair()
        print("[20.3] async let = \(pair.sorted())")
 
        let task = Task {
            await CancellationLab.countUntilCancelled(limit: 1000)
        }
        try? await Task.sleep(for: .milliseconds(25))
        task.cancel()
        let count = await task.value
        print("[20.4] 取消后提前结束 = \(count < 1000)")
 
        let sum = await CancellationLab.add(20, 22)
        print("[20.5] async 函数返回 = \(sum)")
 
        print(
            "[20.6] MemoryLayout<SimulatedDownloader> = \(MemoryLayout<SimulatedDownloader>.size) 字节"
        )
        print("[20.6] MemoryLayout<Task<Int, Never>> = \(MemoryLayout<Task<Int, Never>>.size) 字节")
    }
}