async/await 概念中 async、detach 和 asyncDetached 函数之间的区别

Difference between async, detach and asyncDetached functions in async/await concept

如果我没理解错的话,async, detach and asyncDetached都创建了一个Task(并发单元),简单来说就是允许我们在其中执行await方法。 我能找到的 asyncdetach 之间的唯一区别是 属性 从 调用的 上下文继承的区别(至少优先级)。

我对我对它们之间差异的误解没有任何疑问。但不幸的是,即使在 WWDC 视频中也找不到正确的解释。

名称 asyncdetachedasyncDetach 随着时间的推移而演变。我们现在不调用 async(或 detached)来启动非结构化任务,而只是 Task(priority:operation:). As The Swift Programming Language: Concurrency: Unstructured Concurrency 说:

Unstructured Concurrency

In addition to the structured approaches to concurrency described in the previous sections, Swift also supports unstructured concurrency. Unlike tasks that are part of a task group, an unstructured task doesn’t have a parent task. You have complete flexibility to manage unstructured tasks in whatever way your program needs, but you’re also completely responsible for their correctness. To create an unstructured task that runs on the current actor, call the Task.init(priority:operation:) initializer. To create an unstructured task that’s not part of the current actor, known more specifically as a detached task, call the Task.detached(priority:operation:) class method. Both of these operations return a task handle that lets you interact with the task—for example, to wait for its result or to cancel it.

SE-0304 表示:

A detached task is an unstructured task that is independent of the context in which it is created, meaning that it does not inherit priority, task-local values, or the actor context.

在 WWDC 2021 视频的后半部分也广泛讨论了分离任务 Explore structured concurrency in Swift