swift多线程
使用@MainActor能自动将 func 切换到主线程更新UI,而不用管外部调用到底是在子线程中调用,还是在主线程中调用,。一个async方法,方法内部写了更新 UI操作,在该方法前加了@MainActor后,哪怕在子线程中调用该async方法也不会 crash。
@MainActor func showAndDismissSuccessDialog() async {
await showSuccessDialog()
try? await Task.sleep(nanoseconds: 1000000000)
await dismissSuccessDialog()
}
@MainActor 只能对async/await的代码生效
@MainActor 不会对Callback中的代码生效,例如:
@MainActor class ListViewModel: ObservableObject {
func load() {
loader.loadItems { [weak self] result in
self?.result = result
}
}
}
如果想让@MainActor 对Callback生效,我们需要用withCheckedContinuation将我们的异步callback代码,转换成async/await模式, 例如:
@MainActor func dismissProgressDialog() async {
await withCheckedContinuation { continuation in
dismissProgressDialogSuspending {
continuation.resume(returning: ())
}
}
}
参考:
https://hicc.pro/p/swift/the-main-actor-attribute
https://zhuanlan.zhihu.com/p/395147531
https://www.hackingwithswift.com/articles/233/whats-new-in-swift-5-5