异步数字化 · Swift 并发地图 Async Digitization · Swift Concurrency Atlas

把 async/await 的每一次挂起都可视化 Visualising every async suspension in Swift

主页 hero 以 SVG 动画展示从 async 函数、任务调度、TaskGroup、Actor 到 AsyncSequence 的全流程,让架构设计与中文本地化同频。 The hero SVG animates the complete flow—from async functions and the cooperative task scheduler to TaskGroup, actors, and AsyncSequence—aligning architecture and bilingual narration.

Swift 并发的体验目标 Experience goals for Swift concurrency

“异步数字化” 将 Swift 最新 async 机制拆成可执行模块:左侧 hero 是调度路径,右侧卡片呈现代码约定,全面覆盖 async/await、Task、TaskGroup、Actor、AsyncSequence 以及取消逻辑。 “Async Digitization” decomposes Swift’s latest concurrency primitives into executable modules: the hero visualises scheduling paths while the cards capture code-level conventions across async/await, Task, TaskGroup, actors, AsyncSequence, and cancellation.

async/await 入场 async/await entry point

异步函数默认运行在结构化上下文中,await 只在安全点让出线程;Swift 编译器会在捕获生命周期时进行逃逸检查。 Async functions execute inside structured contexts, yielding only at safe suspension points while the compiler enforces lifetime guarantees.

func fetchArticles() async throws -> [Article] {
    async let summary = fetchSummary()
    let pages = try await fetchPages()
    return try await [summary] + pages
}

Task / TaskGroup Task & TaskGroup

TaskGroup Fan-out fan-in 让 IO 并发仍保持结构化;取消信号会沿父任务向下游传播。 TaskGroup fan-out/fan-in keeps IO concurrency structured while cancellation percolates down the parent chain.

try await withThrowingTaskGroup(of: Report.self) { group in
    for source in sources {
        group.addTask { try await ingest(source) }
    }
    return try await group.reduce(into: []) { $0.append($1) }
}

Actor 隔离 Actor isolation

Actor 用串行执行器包裹可变状态;@MainActor 确保 UI 更新在主线程。 Actors wrap mutable state with a serial executor, while @MainActor guarantees UI mutations on the main thread.

actor TimelineStore {
    private var entries: [TimelineEntry] = []
    func append(_ entry: TimelineEntry) {
        entries.append(entry)
    }
}

AsyncSequence / Stream AsyncSequence & Stream

AsyncSequence 以 backpressure 控制速率,AsyncStream 在闭包中生成值并自动完成或取消。 AsyncSequence imposes backpressure, and AsyncStream yields values inside a closure until completion or cancellation.

let stream = AsyncStream<Event> { continuation in
    eventSource.onValue { continuation.yield($0) }
    eventSource.onComplete { continuation.finish() }
}

Swift async 全流程一览 Swift async end-to-end

  1. 01

    1. async 入口 1. async entry

    swiftc 会把函数包装到异步上下文,插入可挂起点表 (suspend points)。 swiftc wraps the function into an async context and records its suspend points.

  2. 02

    2. 任务调度 2. Task scheduling

    Task 优先级 + cooperative executors 负责把工作单元映射到线程池。 Task priorities plus cooperative executors map work units onto the thread pool.

  3. 03

    3. TaskGroup 拆分 3. TaskGroup fan-out

    withTaskGroup 创建结构化子任务,完成后再 fan-in,以确保取消/错误一致性。 withTaskGroup spins structured children and fans in once they finish for consistent cancellation and error surfaces.

  4. 04

    4. Actor 隔离 4. Actor isolation

    @MainActor / 自定义 actor 执行器串行处理状态,避免 data race。 @MainActor or custom actors serialize access to mutable state to ward off data races.

  5. 05

    5. AsyncSequence 消费 5. AsyncSequence consumption

    for try await 循环按 backpressure(demand)拉取元素,适合流式 UI / I/O。 for try await loops apply demand-driven pulling, ideal for streaming UI or IO.

  6. 06

    6. 取消与恢复 6. Cancellation & resume

    Task.checkCancellation() / withTaskCancellationHandler 在每个挂起点收尾,resume 返回结果或抛错。 Task.checkCancellation() and withTaskCancellationHandler clean up at each suspension before resuming or throwing.