如何恢复继续以确保在 MainActor 上交付结果?

问题描述 投票:0回答:2

我有续集:

func a() async -> Int {
    await withCheckedContinuation { continuation in
        continuation.resume(returning: 3)
    }
}

我希望此函数的所有调用者都能在 MainActor 上收到结果。我不希望调用者必须明确指定此重新安排。我不要这个:

func c() async {
    let three = await a()
    await MainActor.run {
        b(three)
    }
}

我想要的是返回后在主线程上执行的整个代码,直到下一个挂起点,像这样:

func c1() async {
    let three = await a()

    b(three) // Guaranteed main thread, although nothing speaks of it here
}

在某种程度上,我想要

a
声明
I return only on main actor!
,像这样:

func a() @MainActor async -> Int {
    await withCheckedContinuation { continuation in
        continuation.resume(returning: 3)
    }
}

有没有办法做到这一点?

更新: 两位评论者都建议我用

c
注释封闭函数
c1
@MainActor

@MainActor
func c() async {
    let three = await a()
    await MainActor.run {
       b(three)
    }
}

这不像我需要的那样。它说:

  • 每次我等待某人,他们必须在主线程上返回

但我需要的是:

  • 每次有人等我,他们必须在主线程上得到我的结果
swift async-await continuations structured-concurrency
2个回答
0
投票

应该可以这样:

func a() async -> Int {
    await withCheckedContinuation { continuation in
        Task {@MainActor in
            continuation.resume(returning: 3)
        }
    }
}

-1
投票

不,没有办法做到这一点。

如果你等待某个函数,你可以决定它返回哪个线程。 但是作为一个可等待的函数,您不能确保您的结果将在特定和/或主线程上传递给调用者。

© www.soinside.com 2019 - 2024. All rights reserved.