我们怎么知道哪个Thread是用来执行Task的呢?

How can we know which Thread is used to execute Task?

一直以来,我以为非主线程是用来执行任务的

但是,简单的代码片段表明我错了

import UIKit

class X {
    static let INSTANCE = X()
    
    private init() {
        print(">>>> X: outside Task, thread is \(Thread.isMainThread)")
        Task {
            print(">>>> X: inside Task, thread is \(Thread.isMainThread)")
        }
    }
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        _ = X.INSTANCE
        
        print(">>>> ViewController: outside Task, thread is \(Thread.isMainThread)")
        Task {
            print(">>>> ViewController: inside Task, thread is \(Thread.isMainThread)")
        }
    }
}

打印如下

>>>> X: outside Task, thread is true
>>>> ViewController: outside Task, thread is true
>>>> X: inside Task, thread is false
>>>> ViewController: inside Task, thread is true

说明可以使用主线程,也可以使用非主线程来执行任务。

系统如何决定使用哪个线程来执行Task?我不明白上面的例子。

在执行任务之前,ViewControllerX都在主线程中运行。

但是为什么

  1. ViewController 中的任务在主线程中执行。
  2. X中的任务在非主线程中执行。

谢谢。

UIViewController被标记为@MainActor,这意味着任务将在主线程上调度。您的 X class 未标记 @MainActor 因此任务会在任何可用线程上分派。