swift “@MainActor in”和“www.example.com“有区别吗MainActor.run?

k4ymrczo  于 2022-11-21  发布在  Swift
关注(0)|答案(1)|浏览(138)

有什么区别:

Task { await MainActor.run { ... } }

Task { @MainActor in ... }
l7mqbcuq

l7mqbcuq1#

一个区别是一个使用同步闭包,而另一个使用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中,operationasync,这使它成为一个稍微更灵活的机制:

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"
        }
    }
}

我实际上很少使用这两种模式,但这是它们之间的一个区别。

相关问题