I'm hoping someone can help me understand some unexpected behavior in a @MainActor Function which internally calls a task that calls a method on a background actor.
Normally, the function would call the task, pause until the task completes, and finish the end of the function.
However, when the function is annotated @Main actor, the internal task appears to become detached and execute asynchronously such that it finishes after the @MainActor function.
The code below demonstrates this behavior in a playground:
actor SeparateActor{
func actorFunc(_ str:String){
print("\tActorFunc(\(str))")
}
}
class MyClass{
var sa = SeparateActor()
@MainActor func mainActorFunctionWithTask(){
print("mainActorFunctionWithTask Start")
Task{
await self.sa.actorFunc("mainActorFunctionWithTask")
}
print("mainActorFunctionWithTask End")
}
func normalFuncWithTask(){
print("normalFuncWithTask Start")
Task{
await self.sa.actorFunc("normalFuncWithTask")
}
print("normalFuncWithTask End")
}
}
Task{
let mc = MyClass()
print("\nCalling normalFuncWithTask")
mc.normalFuncWithTask()
print("\nCalling mainActorFunctionWithTask")
await mc.mainActorFunctionWithTask()
}
I would expect both the normalFunc and the mainActorFunc to behave the same, with the ActorFunc being called before the end of the task, but instead, my mainActor function completes before the task.
Calling normalFuncWithTask
normalFuncWithTask Start
ActorFunc(normalFuncWithTask)
normalFuncWithTask End
Calling mainActorFunctionWithTask
mainActorFunctionWithTask Start
mainActorFunctionWithTask End
ActorFunc(mainActorFunctionWithTask)