swift多线程之@MainActor

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容