All the while, I thought non-Main thread is used to execute Task
But, the simple code snippet shows I was wrong
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)")
}
}
}
The following is printed
>>>> X: outside Task, thread is true
>>>> ViewController: outside Task, thread is true
>>>> X: inside Task, thread is false
>>>> ViewController: inside Task, thread is true
It shows either Main thread, or non-Main thread can be used to execute Task.
How does the system decide which thread is used to execute Task? I do not understand for the above example.
Before executing Task, both ViewController
and X
are running in Main thread.
But why
- Task in
ViewController
is executed in Main thread. - Task in
X
is executed in non-Main thread.
Thanks.