【发布时间】:2021-12-13 15:33:44
【问题描述】:
在这种情况下,异步函数读取文件并返回解析后的内容。
在我看来,我想从主线程中加载内容,然后在完成后更新视图。
我在各个地方都使用过这种模式,并注意到在某些情况下异步调用在主线程上(通过调试),而在其他情况下它在 Thread 4 Queue : com.apple.root.user-initiated-qos.cooperative (concurrent) 线程上
例如:
struct MyView: View {
@State var data = "some data"
var body: some View {
Button("refresh") {
// when the button is pressed refresh it
Task {
await refresh()
}
}.task {
// when the view appears
await refresh()
}
Text("the data is \(data)") // write the data which was refreshed async
}
}
func refresh() async {
do {
let res = try await anotherAyncFunction()
data = res // this is presumably wrong and off the main thread - obviously might not be correct but leave here for debug as well
} catch {
print("got error \(error)")
}
}
我使用类似的模式创建了几个不同的视图(.task 块调用 async 函数)
在某些情况下,函数会长时间运行(从磁盘读取),并且这发生在主线程上
【问题讨论】:
-
您可能会喜欢视频Swift concurrency: Behind the scenes,它探讨了 Swift 并发调度任务的方式。
标签: swift swiftui swift5.5 swift-concurrency