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.
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 / StreamAsyncSequence & 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
01
1. async 入口1. async entry
swiftc 会把函数包装到异步上下文,插入可挂起点表 (suspend points)。swiftc wraps the function into an async context and records its suspend points.
02
2. 任务调度2. Task scheduling
Task 优先级 + cooperative executors 负责把工作单元映射到线程池。Task priorities plus cooperative executors map work units onto the thread pool.
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.
04
4. Actor 隔离4. Actor isolation
@MainActor / 自定义 actor 执行器串行处理状态,避免 data race。@MainActor or custom actors serialize access to mutable state to ward off data races.
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.
06
6. 取消与恢复6. Cancellation & resume
Task.checkCancellation() / withTaskCancellationHandler 在每个挂起点收尾,resume 返回结果或抛错。Task.checkCancellation() and withTaskCancellationHandler clean up at each suspension before resuming or throwing.