Skip to content

Commit 3aa4fbe

Browse files
committed
Add MainActor.run to execute a synchronous closure on the main thread.
It's important to be able to execute a synchronous closure on the main thread to perform various main-thread updates. This is the async equivalent to DispatchQueue.main.sync.
1 parent d97c867 commit 3aa4fbe

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

stdlib/public/Concurrency/Actor.swift

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,3 +43,17 @@ fileprivate func _registerMainActor(actor: AnyObject)
4343
_registerMainActor(actor: self)
4444
}
4545
}
46+
47+
extension MainActor {
48+
/// Execute the given body closure on the main actor.
49+
public static func run<T>(
50+
resultType: T.Type = T.self,
51+
body: @MainActor @Sendable () throws -> T
52+
) async rethrows -> T {
53+
@MainActor func runOnMain(body: @MainActor @Sendable () throws -> T) async rethrows -> T {
54+
return try body()
55+
}
56+
57+
return try await runOnMain(body: body)
58+
}
59+
}

0 commit comments

Comments
 (0)