【发布时间】: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 注释封闭函数c 和c1。
@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