1

我在一个简单的 Mac 测试项目中有以下代码:

@main
class AppDelegate: NSObject, NSApplicationDelegate {
  func applicationDidFinishLaunching(_ aNotification: Notification) {
    print("are we initially on the main thread: \(Thread.isMainThread)")

    Task {
      print("is new task on main thread: \(Thread.isMainThread)")
    }
  }
}

Swift 语言指南中,我看到以下内容:

要创建在当前参与者上运行的非结构化任务,请调用 Task.init(priority:operation:) 初始化程序。要创建不属于当前参与者的非结构化任务,更具体地称为分离任务,请调用 Task.detached(priority:operation:) 类方法。

因此,由于 AppDelegate 代码在主角上运行并且我正在创建一个普通(即非分离)任务,我希望它的子任务也可以在主角上运行。

但这不是我运行这个测试应用程序时发生的情况:

are we initially on the main thread: true
is new task on main thread: false

根据我对 Swift 并发的了解,我预计新任务将在主要参与者上安排并运行,Thread.isMainThread因此在该任务中是正确的。

为什么不是这样?

4

0 回答 0