John
John

Reputation: 321

What priority will as Task run as when the operation has the @MainActor decorator?

I'm curious what priority the async block() in the code snippet below will run as when the Task's operation is marked @MainActor?

According to the DispatchQueue docs the main queue always runs with a qos of .userInteractive. So I assume the Task's @MainActor operation will also run as .userInteractive - there's only 1 main thread after all.

But since we requested a custom priority for the Task, what priority will the async block run with?

Task<Void, Never>(priority: priority) { @MainActor in
    doStuffOnMainQueue() // .userInteractive
    await block()        // priority?
}

Upvotes: 1

Views: 809

Answers (1)

Rob
Rob

Reputation: 438152

When you add @MainActor qualifier to the closure, that obviously runs on the main actor. But when it reaches await block(), that translates to “suspend the current actor (i.e., the main actor in this case) so it’s free to do other stuff and await the results of the block().”

Regarding the question of what priority the block() uses, that depends on how it was declared. Assuming block() is just a closure that you passed to this method, then in my experience it runs with the priority that you supplied to Task, not the main actor. But there are lots of variables (e.g., you could specify @MainActor for that closure parameter, too; you could be calling some method running on some other actor; etc.), so we cannot get more specific without seeing a reproducible example.

But, bottom line, when you await something, the actor/priority of the awaited code is dictated by how you defined that, rather than the context of the code from which you called it.

Upvotes: 1

Related Questions