這個問題在這里已經有了答案: 什么決定了 Swift 5.5 任務初始化程式是否在主執行緒上運行? (1 個回答) 昨天關門。
一直以來,我認為非主執行緒用于執行任務
但是,簡單的代碼片段表明我錯了
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?我不明白上面的例子。
在執行任務之前,兩者ViewController都X在主執行緒中運行。
但為什么
- 任務在
ViewController主執行緒中執行。 - 任務在
X非主執行緒中執行。
謝謝。
uj5u.com熱心網友回復:
UIViewController被標記@MainActor,這意味著任務將在主執行緒上分派。您的X類未標記@MainActor,因此任務在任何可用執行緒上分派。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/464492.html
