【问题标题】:swift calling async function without a return value快速调用没有返回值的异步函数
【发布时间】:2022-01-03 08:38:52
【问题描述】:

在 swift 的新结构化并发模型中是否有在没有虚拟 bool 返回的情况下执行以下操作?

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

我知道我可以执行以下操作,但不会同时运行:

func do() async {
  something()
}
await do()
stuff()

//cannot run "stuff" and "do" concurrently

我觉得我在这里遗漏了一个基本概念,因为顶部的代码块可以满足我的需要,但由于返回 Bool,感觉就像是 hack。

【问题讨论】:

    标签: swift async-await concurrency


    【解决方案1】:

    您所描述的是一个任务。例如:

    Task { await `do`() }
    stuff()
    

    这将同时运行do()stuff()。如果您需要跟踪 do() 何时完成,您可以等待任务的值:

    let task = Task { await `do`() }
    stuff()
    await task.value // Doesn't actually return anything, but will block
    

    这种Task在当前Actor的上下文中运行,这通常是你想要的。如果你想要独立于当前 Actor 的东西,你可以使用 Task.detached() 代替。

    如果您以前使用过 DispatchQueues,在许多地方您会写 queue.async { ... },现在您可以写 Task { ... }。新系统功能更强大,但如果您愿意,它可以很好地映射到旧系统。

    【讨论】:

      【解决方案2】:

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-22
        • 2019-02-16
        • 1970-01-01
        • 2018-01-03
        • 1970-01-01
        • 1970-01-01
        • 2021-04-04
        • 1970-01-01
        相关资源
        最近更新 更多