Post

Replies

Boosts

Views

Activity

Reply to Task on MainActor does not run on the main thread, why?
Thanks for the great answer @eskimo. It's quite clear from your answer and the design of Swift async-await that if one were to force some code to run on the main thread, than it should be designed that way at compile time. Otherwise, the way code is executed is pretty much thread-blind. I have one more question regarding this issue: if you were to have the same logic run sometimes on the main thread but at other times on any other thread, do you have to declare two methods and have one marked @MainActor? P.S. I was hoping that Swift async-await would turn out to be something like Kotlin coroutines. I was so confused at first. We'll see if this indeed achieves the goal Swift is trying to solve. P.P.S I'll post some code that helped me understand the behavior somewhat. Hopefully it will help others too. class SomeClass { func runSomeWorkAnywhere(_ taskNumber: Int) async { print(#function, "#\(taskNumber)", Thread.current) } @MainActor func runOnMain() { print(#function, Thread.current) Task { @MainActor in print(#function, "task #1", Thread.current) await runSomeWorkAnywhere(1) } Task { print(#function, "task #2", Thread.current) await runSomeWorkAnywhere(2) } Task.detached { [unowned self] in print(#function, "task #3", Thread.current) await runSomeWorkAnywhere(3) } } func runRogue() async { print(#function, Thread.current) Task { @MainActor in print(#function, "task #1", Thread.current) } Task { print(#function, "task #2", Thread.current) } Task.detached { print(#function, "task #3", Thread.current) } } } let obj = SomeClass() Task { print("top-level task", Thread.current) await obj.runOnMain() await obj.runRogue() }
Jul ’23