Swift Concurrency question (Swift 5, no approachable concurrency, nonisolated default actor isolation): when you add a simple Task block in a func in a view controller, I thought it always executes on the main thread if the callee invokes that func while on main. If you want to run code on a background thread, you implement an async func and call it in the Task, but the next line in the Task would still be back on main. Is that wrong, any line in the Task body can run on any thread??
@jordanhipwell you wanna throw that question into a gist?
@mattiem Something like this, I thought I knew this super basic thing years ago šŸ˜…
@jordanhipwell can you maybe annotate the code with a more specific part you are confused by. I’m still not 100% sure I understand the question.

@mattiem My expectation was the Task body would always start executing on the main thread, execute the async StoreKit function on a background thread, then execute the remaining code on main thus ensuring all UI updates (loadingView, alert) occur on main.

But I'm getting rare/random crashes modifying auto layout on a background thread (only in one app where I have this pattern in place, not my other app interestingly), making me question everything šŸ˜…

@jordanhipwell I don’t see how this Task’s body could execute *off* the main thread. However it’s slightly hard to be 100% sure because I can’t poke around to verify. But this is statically-defined so we can figure it out. What matters here is ā€œbuyProductā€. Task with inherit whatever that is defined to use.

@jordanhipwell @mattiem unless the Task is annotated @MainActor it will be on the global executor.

So if you switch this to:

Task { @MainActor in

}

@murfin @jordanhipwell that is only true if the enclosing method is nonisolated, which I think is really what’s at issue here.
@jordanhipwell it’s not about whether you invoke the func while on the main thread. The Task there inherits main-actor-ness from being declared inside a MainActor func (inherited from being declared in a MainActor type). So no matter which thread calls buyProduct(), the lines of code inside the task will always run on the main actor.
@bjhomer That's a good clarification that makes sense, thanks! With this pattern I expected it to never execute the UI code on a background thread, but that's happening in the app update where I added some Tasks like this within view controller functions or another @ MainActor class (seemingly just like I did in another app that's not crashing so I'm quite confused šŸ¤”). Codex is adamant though unstructured tasks Task { } do not inherit actor isolation so it's possible it won't run on main.
@jordanhipwell , yeah, that is surprising to me. I would guess there is something else going on that’s interfering.