【问题标题】:How to resume a continuation ensuring that the result is delivered on the MainActor?如何恢复继续以确保结果在 MainActor 上传递?
【发布时间】:2022-08-17 01:51:47
【问题描述】:

我有一个延续:

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

相反,我想要的是整个代码在返回后在 MainThread 上执行,直到下一个暂停点,如下所示:

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

有没有办法做到这一点?

更新:两位评论者都建议我用@MainActor 注释封闭函数cc1

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

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

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

但我需要的是这个:

  • 每次有人在等我时,他们必须在主线程上得到我的结果
  • 使用 @MainActor 注释函数。
  • @MainActor func a() async -> Int { ... }
  • 嘿伙计们,谢谢你们的 cmets,但不幸的是他们没有解决我正在谈论的问题

标签: swift async-await continuations structured-concurrency


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2017-06-06
    • 1970-01-01
    • 2016-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-05
    相关资源
    最近更新 更多