difference between `MainActor.run` and `Task {@MainActor in...}`
Asked on 05/16/2025
1 search
The difference between MainActor.run
and Task {@MainActor in...}
lies in how they handle execution on the main actor in Swift's concurrency model.
-
MainActor.run
: This is a synchronous way to execute code on the main actor. It ensures that the code block is executed on the main actor, but it does not create a new asynchronous task. This is useful when you need to perform operations on the main actor without introducing additional asynchronous behavior. -
Task {@MainActor in...}
: This creates a new asynchronous task that is executed on the main actor. It is useful when you want to perform asynchronous operations that need to be isolated to the main actor. This approach is more flexible as it allows for asynchronous code execution, which can be beneficial for tasks that involve waiting for results or performing non-blocking operations.
In summary, use MainActor.run
for synchronous operations that need to be on the main actor, and Task {@MainActor in...}
for asynchronous operations that should be isolated to the main actor.

Go further with Swift Testing
Learn how to write a sweet set of (test) suites using Swift Testing’s baked-in features. Discover how to take the building blocks further and use them to help expand tests to cover more scenarios, organize your tests across different suites, and optimize your tests to run in parallel.

Explore Swift performance
Discover how Swift balances abstraction and performance. Learn what elements of performance to consider and how the Swift optimizer affects them. Explore the different features of Swift and how they’re implemented to further understand the tradeoffs available that can impact performance.

Consume noncopyable types in Swift
Get started with noncopyable types in Swift. Discover what copying means in Swift, when you might want to use a noncopyable type, and how value ownership lets you state your intentions clearly.