0

I am initialising a class, MyClass from a MainActor. Inside the init() of MyClass I have a Task. I thought that this task would run on the main thread because I thought tasks are supposed to inherit the thread of their parent unless they're detached. However, it doesn't. It's always called on a background thread, unless I mark MyClass with @MainActor. Why?

final class MyClass {
  static var shared = MyClass()

  init() {
    print("Main thread?", Thread.isMainThread) // True
    Task {
      print("Main thread?", Thread.isMainThread) // False
    }
  }

  static func configure() {
    shared = MyClass()
  }
}

Task { @MainActor in
   MyClass()
}
Tometoyou
  • 7,792
  • 12
  • 62
  • 108
  • `Task { @MainActor in ...`, I have never seen this before pattern before. – Joakim Danielson Nov 16 '22 at 12:45
  • I'm using it as an example for how I'm calling it from a main actor isolated context... That's not the issue here – Tometoyou Nov 16 '22 at 12:46
  • Compare https://stackoverflow.com/questions/67954414/what-determines-whether-a-swift-5-5-task-initializer-runs-on-the-main-thread – matt Nov 16 '22 at 12:51
  • MyClass does not "have" a "thread". It has no characteristic at all with regard to "threads", unless, as you rightly say, you give it one. All _you_ did was call this class's _initializer_ on the main actor. That has _no_ effect on subtasks created within this class's code. Marking the class _itself_ as main actor is a different matter altogether. – matt Nov 16 '22 at 12:58
  • But really you need to stop thinking in terms of threads. Try to pretend you'd never heard of them! There are only actors and tasks. If code is not in an actor or marked for an actor, you have no right to expect _anything_. – matt Nov 16 '22 at 13:00

0 Answers0