This is sort of a follow-up to my earlier asyncDetached falling back into main thread after MainActor call.
Here's the complete code of an iOS view controller:
import UIKit
func test1() {
print("test1", Thread.isMainThread) // true
Task {
print("test1 task", Thread.isMainThread) // false
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
test1()
test2()
}
func test2() {
print("test2", Thread.isMainThread) // true
Task {
print("test2 task", Thread.isMainThread) // true
}
}
}
The two functions test1
and test2
are identical, and are being called from the very same place. Yet one of them runs its Task initializer operation:
function on a background thread, and the other runs on the main thread.
What determines this? I can only think it has to do with where the method is declared. But what does it have to do with where the method is declared?