0

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

  1. Task in ViewController is executed in Main thread.
  2. Task in X is executed in non-Main thread.

Thanks.

Cheok Yan Cheng
  • 47,586
  • 132
  • 466
  • 875

1 Answers1

1

UIViewController is marked @MainActor which means that tasks will be dispatched on the main thread. Your X class is not marked @MainActor so tasks are dispatched on any available thread.

Paulw11
  • 108,386
  • 14
  • 159
  • 186