glo*_*loo 3 concurrency async-await swift
无论如何,Swift 的新结构化并发模型是否可以在没有虚拟布尔返回的情况下执行以下操作?
func do() async -> Bool {
something()
return true
}
async let foo = do()
//do other stuff
stuff()
//now I need to know that "do" has finished
await foo
Run Code Online (Sandbox Code Playgroud)
我知道我可以执行以下操作,但它不会同时运行:
func do() async {
something()
}
await do()
stuff()
//cannot run "stuff" and "do" concurrently
Run Code Online (Sandbox Code Playgroud)
我觉得我在这里缺少一个基本想法,因为顶部的代码块做了我需要的事情,但由于 Bool 返回,感觉像是黑客攻击。
Swift 隐式返回Void非返回函数,所以我想这会很好
func do() async {
something()
}
async let foo: Void = do() // just explicit Void so the compiler doesn't emit a warning telling you that may not be expected
//do other stuff
stuff()
//now I need to know that "do" has finished
await foo
Run Code Online (Sandbox Code Playgroud)
你所描述的是一个任务。例如:
Task { await `do`() }
stuff()
Run Code Online (Sandbox Code Playgroud)
这将do()与同时运行stuff()。如果您需要跟踪何时do()完成,您可以等待任务的值:
let task = Task { await `do`() }
stuff()
await task.value // Doesn't actually return anything, but will block
Run Code Online (Sandbox Code Playgroud)
这种Task运行在当前Actor的上下文中,这通常就是你想要的。如果您想要独立于当前 Actor 的东西,您可以使用Task.detached()。
如果您以前使用过 DispatchQueues,那么在许多您本来应该编写的地方queue.async { ... },您现在可以编写Task { ... }。新系统更加强大,但如果您愿意的话,它可以很好地映射到旧系统。
| 归档时间: |
|
| 查看次数: |
4811 次 |
| 最近记录: |