In an Interactive Server Blazor component, why does calling StateHasChanged from a System.Threading.Timer callback throw, and how does InvokeAsync fix it?
answer
- the renderer's Dispatcher
- one logical thread per circuit
- "not associated with the Dispatcher"
- await InvokeAsync(StateHasChanged)
- single-threaded WebAssembly hides the bug
basics
~20 sRendering must happen on the renderer's Dispatcher, and a Timer callback runs on a thread-pool thread, so StateHasChanged throws an InvalidOperationException saying the thread is not associated with the Dispatcher. Wrapping the call in InvokeAsync runs it on the Dispatcher.
solid answer
~40 sEach Blazor renderer has a `Dispatcher`. On Interactive Server it is a synchronization context per **circuit** that runs work on one logical thread at a time, so component code never runs concurrently within a circuit. Rendering asserts that it is on that dispatcher; a `System.Threading.Timer` or `System.Timers.Timer` callback, or an event raised by a singleton service, arrives on a thread-pool thread, so `StateHasChanged` throws `InvalidOperationException`: "The current thread is not associated with the Dispatcher. Use InvokeAsync() to switch execution...". The fix is `await InvokeAsync(StateHasChanged)`, or `InvokeAsync(async () => { forecast = await ...; StateHasChanged(); })` to update state and render together. On single-threaded WebAssembly the dispatcher's access check always passes, so the bug hides there and appears when the component runs on the server, for example under Auto.
code
razor · 21 lines@implements IDisposable
@inject IForecastClient Forecasts
<p>@forecast?.Summary</p>
@code {
[Parameter] public int FieldId { get; set; }
private Forecast? forecast;
private Timer? timer;
protected override void OnInitialized()
=> timer = new Timer(_ => _ = RefreshAsync(), null, TimeSpan.Zero, TimeSpan.FromMinutes(10));
private Task RefreshAsync() => InvokeAsync(async () =>
{
forecast = await Forecasts.GetAsync(FieldId);
StateHasChanged();
});
public void Dispose() => timer?.Dispose();
}go deeper
Remember that code outside Blazor's own events, such as a timer, must call InvokeAsync(StateHasChanged) to refresh the UI.
Explain the dispatcher and per-circuit synchronization context, the exact exception, and why state updates belong inside the InvokeAsync delegate.
Choose between callback timers and awaited PeriodicTimer loops, handle singleton events per circuit, avoid blocking calls, and route background exceptions with DispatchExceptionAsync.
Make components render-mode agnostic by policy - InvokeAsync for every external callback, no blocking calls - so code proven on WebAssembly does not break on the server.
## The rule: component work happens on the dispatcher Every Blazor renderer exposes a `Dispatcher` (abstract class in `Microsoft.AspNetCore.Components`). Its job is to make component code behave as if it were single-threaded: - On **Interactive Server**, each circuit has its own synchronization context. Work for that circuit runs on one thread at a time, so two event handlers of the same user never run in parallel, while different circuits run in parallel. - On **Interactive WebAssembly** without multithreading, the browser's main thread is the only thread, and the renderer uses a dispatcher whose `CheckAccess()` always returns `true`. Lifecycle methods, event handlers and `EventCallback` invocations are already called on the dispatcher, and the continuations after their `await`s resume there. Code that starts somewhere else is the problem. ## What throws, and why A farm dashboard's `WeatherWidget` refreshes every ten minutes. Written with `System.Threading.Timer`: 1. The timer callback runs on a **thread-pool thread**, outside the circuit's synchronization context. 2. The callback updates `forecast` and calls `StateHasChanged()`. 3. `StateHasChanged` asks the renderer to queue a render; the renderer calls `Dispatcher.AssertAccess()`. 4. `AssertAccess` finds the current thread is not the dispatcher's and throws `InvalidOperationException`: "The current thread is not associated with the Dispatcher. Use InvokeAsync() to switch execution to the Dispatcher when triggering rendering or component state." The same happens for a `System.Timers.Timer` `Elapsed` handler, a `Task.Run` continuation, or a C# event raised by a singleton service (a message bus, a sensor feed) from its own thread. ## The fix: InvokeAsync `ComponentBase` exposes `InvokeAsync(Action)` and `InvokeAsync(Func<Task>)`, which hand the work to the dispatcher and return a `Task` that completes when it has run: | Code | Effect | |---|---| | `await InvokeAsync(StateHasChanged);` | queues the render on the dispatcher | | `await InvokeAsync(() => { forecast = latest; StateHasChanged(); });` | updates state and renders without racing other component code | | `await InvokeAsync(async () => { forecast = await client.GetAsync(id); StateHasChanged(); });` | runs async work whose continuations stay on the dispatcher | Updating the fields **inside** the `InvokeAsync` delegate matters: assigning `forecast` on the timer thread while the component is rendering on the dispatcher is a data race even if the render call itself is marshalled. ## Alternatives and related rules - An **async loop started from a lifecycle method**, for example `PeriodicTimer.WaitForNextTickAsync` awaited in a method kicked off in `OnInitialized`, resumes on the dispatcher after each `await`, so it may call `StateHasChanged` directly. That is often simpler than a callback timer. - **Do not block** with `.Result`, `.Wait()` or `Thread.Sleep` inside component code: on the server that ties up a thread of the circuit's context and can deadlock or starve the thread pool. - **Re-entrancy still exists.** A single logical thread does not mean a single flow: at every `await`, other lifecycle methods, event handlers or disposal may run, so state must be valid before each `await`. - **Exceptions outside the lifecycle** - in a timer callback, say - do not reach an `ErrorBoundary` by themselves; `DispatchExceptionAsync(ex)` hands them to the component's error handling as if a lifecycle method had thrown. ## Why it works in WebAssembly and fails on the server Because the single-threaded WebAssembly dispatcher's access check always succeeds, a timer that calls `StateHasChanged` directly appears to work under Interactive WebAssembly. The same component under Interactive Server - or under Interactive Auto on a first visit, when it runs on the server - throws. Writing `InvokeAsync` everywhere such callbacks occur keeps a component correct in every render mode.
- A singleton FarmAlerts service raises an AlertRaised event that several components handle. What do the handlers need?Each handler must marshal onto its own component's dispatcher with `InvokeAsync`, because the event is raised on whatever thread the service uses and each circuit has its own dispatcher. The components must also unsubscribe in `Dispose`/`DisposeAsync`; otherwise the singleton keeps every closed component and its circuit alive and keeps calling into disposed components.
- Can InvokeAsync be used to defer work until after the current method returns?Not reliably. The Blazor docs warn that passing work to `InvokeAsync` may only defer it until the next `await` is reached, because the dispatcher can run it as soon as the current flow yields. Use it to get onto the dispatcher, not as a scheduling primitive.
- StateHasChanged is thread-safe, so it can be called from any thread on the server.
- Interactive Server runs each user's component code on many threads in parallel.
- If the timer code works under WebAssembly it is correct for every render mode.
- Calling .Result on the HTTP task inside a component avoids the threading problem.
- InvokeAsync starts the delegate on a new background thread to keep the UI free.