小编Shu*_*oto的帖子

使用 Swift async、await、@MainActor 的后台任务的最佳解决方案是什么

我\xe2\x80\x99m 正在学习Swift asyncawait、 。@MainActor

\n

我想运行一个很长的过程并显示进度。

\n
import SwiftUI\n\n@MainActor\nfinal class ViewModel: ObservableObject {\n    @Published var count = 0\n\n    func countUpAsync() async {\n        print("countUpAsync() isMain=\\(Thread.isMainThread)")\n        for _ in 0..<5 {\n            count += 1\n            Thread.sleep(forTimeInterval: 0.5)\n        }\n    }\n\n    func countUp() {\n        print("countUp() isMain=\\(Thread.isMainThread)")\n        for _ in 0..<5 {\n            self.count += 1\n            Thread.sleep(forTimeInterval: 0.5)\n        }\n    }\n}\n\nstruct ContentView: View {\n    @StateObject private var viewModel = ViewModel()\n\n    var body: some View {\n        VStack {\n            Text("Count=\\(viewModel.count)")\n                .font(.title)\n\n            Button("Start Dispatch") {\n                DispatchQueue.global().async {\n …
Run Code Online (Sandbox Code Playgroud)

asynchronous async-await swift mainactor

8
推荐指数
1
解决办法
9404
查看次数

标签 统计

async-await ×1

asynchronous ×1

mainactor ×1

swift ×1