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()
}