Documenting what @MainActor actually does

tldr; I have tried to document the rules myself, and would appreciate feedback:
https://blog.hobbyistsoftware.com/2022/11/mainactor-the-rules/


I have been banging on for a while about how Apple/Swift should document what @MainActor actually does.

This has bubbled up in a separate discussion about warnings when @MainActor rules are broken

Which in turn reference some blog posts I have written on the subject.
https://blog.hobbyistsoftware.com/2022/11/five-ways-to-break-swift-concurrency/
https://blog.hobbyistsoftware.com/2022/01/mainactor-not-guaranteed/

Given that there is not currently any documentation that I'm aware of - I have had a go at writing 'the rules'

Specifically, I'm trying to document what is considered @MainActor, and when those rules are ignored.

https://blog.hobbyistsoftware.com/2022/11/mainactor-the-rules/

I'd appreciate any feedback - as I suspect I have missed some edge cases...

5 Likes

One of the first times I came across this in my own code was when using NSAlert in MacOS

Clicking the ‘ok’ button sometimes called back on a background thread.

The thread where a piece of code executes is an implementation detail and should not be rely on to determine if your code is safe to use a specific actor.

I'm pretty sure it is safe to call UI code from NSAlert callback (like any other AppKit callback). It may execute on a background thread, but guarantee to be safe to call other @MainActor function, as the main thread may be blocking while waiting for the callback to end.

It may be now - but that is exactly how I got bitten some time back!