Why do you sometimes need to wrap StateHasChanged in InvokeAsync, and what is the renderer's synchronization context?
Last updated
The renderer's synchronization context is a single logical thread that serializes rendering and event handling so UI state is never touched concurrently.
Code running off that context (
System.Timers.Timercallbacks,Task.Run, events from non-UI services) can throw or race if it callsStateHasChangeddirectly.InvokeAsyncdispatches the delegate back onto the renderer's context so the update is safe. Event handlers and lifecycle methods already run there.
- https://learn.microsoft.com/en-us/aspnet/core/blazor/components/synchronization-context?view=aspnetcore-10.0
- https://learn.microsoft.com/es-es/aspnet/core/blazor/state-management/?view=aspnetcore-12.0
- https://learn.microsoft.com/en-us/aspnet/core/blazor/components/rendering?view=aspnetcore-10.0
- https://github.com/microsoft/fluentui-blazor/issues/506
- https://dev.to/preeti_islur_08045d6b7089/fixing-blazor-server-concurrency-issues-signalr-circuits-statehaschanged-and-thread-safety-11io
- https://blazor-university.com/components/multi-threaded-rendering/invokeasync/