Discussion about this post

User's avatar
Ivelin Davidov's avatar

Unstructured tasks inherit the actor context they’re created in. In your example, since the task is created inside a UIViewController, it runs on the MainActor, meaning any code in the task will be executed on the main thread.

Apple covers this in WWDC 2021 Session 10134 - https://developer.apple.com/videos/play/wwdc2021/10134/?time=1273.

If you don’t want a task to inherit the actor context, you can use Task.detached. Just be careful—this can lead to issues like running UIKit code on a background thread, which isn’t safe.

Expand full comment
Lucas Derraugh's avatar

In your example of the 2 prints on main, I assume the first comes from a method (or class) that is MainActor bound? If so, can’t you still use Task { someMainActorBoundEntity.syncMethod() } and this will be guaranteed to run on main? Is it the fact that the only enclosed content is a print statement mean an optimization is made to not require main execution?

Expand full comment
2 more comments...

No posts