gpt4 book ai didi

swift - 从无任务上下文创建常规或分离任务的区别?

转载 作者:行者123 更新时间:2023-12-05 01:24:10 26 4
gpt4 key购买 nike

在无任务上下文(例如,从一些随机的 AppKit 代码)中创建 Task 时,创建分离任务或常规任务之间有区别吗?例如调用

  • Task.detached
  • Task.init

由于该任务没有可继承的参与者,我认为这 2 个调用必须是等效的,或者是否仍需要考虑实现差异?

最佳答案

首先,重要的是要注意这些都不会创建子任务。 structured 创建了一个子任务并发构造,如 awaiting 一个 async 函数、async let 或任务组,而不是像 Task.init< 这样的非结构化并发Task.detached

In addition to the structured approaches to concurrency described in the previous sections, Swift also supports unstructured concurrency. [...] 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.

这也记录在 Task.init 中(我的粗体)

Runs the given nonthrowing operation asynchronously as part of a new top-level task on behalf of the current actor.

您还可以在实际操作中看到这一点 - 通过等待异步函数创建的子任务在其父任务被取消时被取消,但由 Task.init 创建的任务则不会。

let task = Task {
let notChild = Task {
await Task.sleep(1_000_000_000)
if !Task.isCancelled {
print("Not Child!")
} else {
print("Child!")
}
}
}
task.cancel()
// prints "Not Child!"
func childTask() async {
await Task.sleep(1_000_000_000)
if !Task.isCancelled {
print("Not Child!")
} else {
print("Child!")
}
}

let task = Task {
await childTask()
}
task.cancel()
// prints "Child!"

无论如何,回到你的问题,那么 Task.initTask.detached 之间到底有什么区别?我的回答中的第一句话稍微说明了这一点,Task.init 的文档中也提到了这一点:

Like Task.detached(priority:operation:), this function creates a separate, top-level task. Unlike Task.detached(priority:operation:), the task created by Task.init(priority:operation:) inherits the priority and actor context of the caller, so the operation is treated more like an asynchronous extension to the synchronous operation.

本质上,它是关于执行任务的actor,所以即使没有当前任务,但有一个当前actor,Task.initTask.detached 仍然会做不同的事情。 Task.init 将在当前 actor 上运行任务,而 Task.detached 将运行与任何 actor 分离的任务。

另请参阅:https://www.hackingwithswift.com/quick-start/concurrency/whats-the-difference-between-a-task-and-a-detached-task

关于swift - 从无任务上下文创建常规或分离任务的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71575803/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com