有什么区别:
Task { await MainActor.run { ... } }
和
Task { @MainActor in ... }
l7mqbcuq1#
一个区别是一个使用同步闭包,而另一个使用async闭包,具体来说,run使用同步闭包(即,body * 不是 * async):
async
run
body
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,这使它成为一个稍微更灵活的机制:
Task.init
operation
public init(priority: TaskPriority? = nil, operation: @escaping @Sendable () async -> Success)
因此,为了说明差异,请考虑:
Task { @MainActor in statusText = "Fetching" await viewModel.fetchData() statusText = "Done" }
但不能在MainActor.run中使用await:
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
Task { await MainActor.run { Task { statusText = "Fetching" await viewModel.fetchData() statusText = "Done" } } }
我实际上很少使用这两种模式,但这是它们之间的一个区别。
1条答案
按热度按时间l7mqbcuq1#
一个区别是一个使用同步闭包,而另一个使用
async
闭包,具体来说,run
使用同步闭包(即,body
* 不是 *async
):这非常适合这样的场景:您在某个其他参与者上,但希望运行一系列三个方法,所有这些方法都与主参与者隔离,但希望使用单个上下文切换(而不是三个)来完成此操作。
但是,在
Task.init
中,operation
是async
,这使它成为一个稍微更灵活的机制:因此,为了说明差异,请考虑:
但不能在
MainActor.run
中使用await
:你必须在里面插入另一个
Task
。(!)我实际上很少使用这两种模式,但这是它们之间的一个区别。