我理解异步Swift任务不应该阻塞(异步工作线程必须始终向前推进).
这是正确的.Swift并发系统的基石是任务必须始终向前推进.
我可以使用withCheckedContinuation
的主体来启动一个线程,将延续句柄复制到该线程并调用延续吗.完成后从该线程继续?
是的,这也是正确的,这正是延续的目的:
CheckedContinuation
A mechanism to interface between synchronous and asynchronous code, logging correctness violations.
继续的目的是让您将阻塞同步操作适应async
世界.当你打withCheckedContinuation
,它
[s] uspends当前任务,然后调用给定的闭包,并为当前任务判断continuation.
任务将无限期暂停,直到您恢复它,这允许其他任务在此期间取得进展.您获得的继续值是一个线程安全接口,用于指示阻塞操作已完成,并且原始任务应在下一个可用机会时恢复.延续也是Sendable,这表示可以在线程之间安全地传递它.任何线程都可以继续执行任务,因此您甚至不必回调同一线程上的继续.
SE-0300: Continuations for interfacing async tasks with synchronous code的用法示例:
func operation() async -> OperationResult {
// Suspend the current task, and pass its continuation into a closure
// that executes immediately
return await withUnsafeContinuation { continuation in
// Invoke the synchronous callback-based API...
beginOperation(completion: { result in
// ...and resume the continuation when the callback is invoked
continuation.resume(returning: result)
})
}
}
请注意,这仅适用于真正阻塞的任务,并且在完成它们所依赖的某些任务之前无法取得进一步的进展.这与执行主动计算的任务不同,主动计算恰好需要很长的时间,因为这些任务至少正在取得主动进展.(但在聊天中,你澄清你的用例是前者.)