在这种情况下,异步函数读取文件并返回解析的内容。
在我看来,我想从主线程中加载内容,然后在完成后更新视图。
我在各个地方都使用过这种模式,并注意到在某些情况下异步调用在主线程上(通过调试),而在其他情况下它在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
函数)
在某些情况下,函数长时间运行(从磁盘读取)并且发生在主线程上