这两种方式有什么区别吗:
Task { await MainActor.run { ... } }
和
Task { @MainActor in ... }
这两种方式有什么区别吗:
Task { await MainActor.run { ... } }
和
Task { @MainActor in ... }
一个区别是一个使用同步闭包,而另一个使用async
闭包。具体来说,run
使用同步闭包(即,body
不是async):
public static func run<T>(resultType: T.Type = T.self, body: @MainActor @Sendable () throws -> T) async rethrows -> T where T : Sendable
Task.init
中,operation
是async
,这使得它成为一个稍微更灵活的机制:public init(priority: TaskPriority? = nil, operation: @escaping @Sendable () async -> Success)
因此,为了说明区别,请考虑:
Task { @MainActor in
statusText = "Fetching"
await viewModel.fetchData()
statusText = "Done"
}
但是你不能在MainActor.run
中使用await
:
Task {
await MainActor.run { // Cannot pass function of type '@Sendable () async -> ()' to parameter expecting synchronous function type
statusText = "Fetching"
await viewModel.fetchData()
statusText = "Done"
}
}
Task
。(!)Task {
await MainActor.run {
Task {
statusText = "Fetching"
await viewModel.fetchData()
statusText = "Done"
}
}
}
我其实很少同时使用这两种模式,但这是它们之间的一个区别。