In a Blazor weather widget that polls on a timer and holds a JavaScript chart, how should IAsyncDisposable be implemented, and when does Blazor call it?
answer
- @implements IAsyncDisposable
- called when removed from the UI
- only DisposeAsync if both are implemented
- cancel the CancellationTokenSource
- no StateHasChanged in DisposeAsync
basics
~20 sAdd @implements IAsyncDisposable and, in DisposeAsync, cancel pending work, stop the timer, unsubscribe from service events and release JavaScript objects. Blazor calls it when the component leaves the UI or, on the server, when its circuit is torn down; with both interfaces only DisposeAsync runs.
solid answer
~50 s`ComponentBase` implements neither `IDisposable` nor `IAsyncDisposable`; a component opts in with `@implements IAsyncDisposable` and a `public async ValueTask DisposeAsync()`. Blazor calls it when the component is removed from the render tree - a parent stops rendering it, its `@key` changes, the user navigates away - and when the renderer itself is disposed, for example when a circuit ends. If a component implements both interfaces, only `DisposeAsync` is called. In it: cancel a `CancellationTokenSource` that every load received, dispose the `PeriodicTimer` so its loop exits, unsubscribe from events on longer-lived services (otherwise they keep the component alive), and dispose `IJSObjectReference`s. Do not rely on timing: disposal can happen before an awaited `OnInitializedAsync` resumes, so code after an `await` should tolerate a disposed component, and `StateHasChanged` in `DisposeAsync` is not supported. Keep it fast; the framework does not time it out for you.
code
razor · 32 lines@implements IAsyncDisposable
@inject IForecastClient Forecasts
<p>@forecast?.Summary</p>
@code {
[Parameter] public int FieldId { get; set; }
private readonly CancellationTokenSource cts = new();
private PeriodicTimer? timer;
private Forecast? forecast;
protected override void OnInitialized() => _ = PollAsync();
private async Task PollAsync()
{
timer = new PeriodicTimer(TimeSpan.FromMinutes(10));
do
{
forecast = await Forecasts.GetAsync(FieldId, cts.Token);
StateHasChanged();
}
while (await timer.WaitForNextTickAsync(cts.Token));
}
public ValueTask DisposeAsync()
{
cts.Cancel();
timer?.Dispose();
cts.Dispose();
return ValueTask.CompletedTask;
}
}go deeper
Know that components holding timers, subscriptions or JavaScript objects implement IDisposable or IAsyncDisposable with @implements and clean up there.
Explain when Blazor calls disposal, that only DisposeAsync runs if both interfaces exist, and what to cancel, dispose and unsubscribe.
Prevent circuit memory leaks and post-disposal work: cancellation tokens through every load, disposed-flag checks after awaits, and safe JavaScript cleanup on disconnected circuits.
Make disposal part of the component checklist and code review, and track server memory per circuit so leaked subscriptions are caught before they reach production scale.
## Why components need disposal A Blazor component can outlive the page section that shows it only if something keeps it alive. A farm dashboard's `WeatherWidget` might: - run a polling loop every ten minutes; - have an HTTP request in flight; - be subscribed to a `FieldSelectionChanged` event on a scoped or singleton service; - hold an `IJSObjectReference` to a chart object in the browser. If the user removes the widget from the dashboard, none of that stops by itself. On Interactive Server, a forgotten subscription on a singleton keeps the component - and through it, the circuit's objects - in memory and keeps calling into a component that is no longer rendered. ## How Blazor disposes components `ComponentBase` does not implement disposal itself. A component opts in with the `@implements` directive: - `@implements IDisposable` with `public void Dispose()` for synchronous cleanup; - `@implements IAsyncDisposable` with `public ValueTask DisposeAsync()` when cleanup awaits something, such as disposing a JavaScript object reference. The renderer disposes a component when it is **removed from the UI**: 1. a parent's render no longer includes it (an `@if` turns false, a list item disappears); 2. its `@key` changes, so the old instance is replaced; 3. navigation replaces the page that contains it; 4. the renderer itself is disposed, for example when an Interactive Server circuit is torn down. If a component implements **both** interfaces, the renderer calls only `DisposeAsync`. The docs add that components should not need both, and that `DisposeAsync` must not take long. ## What DisposeAsync should do | Resource | Cleanup | |---|---| | in-flight loads | `cts.Cancel()` on a `CancellationTokenSource` whose token every call received | | `PeriodicTimer` loop | `timer.Dispose()`, after which `WaitForNextTickAsync` returns `false` and the loop ends | | `System.Threading.Timer` | `await timer.DisposeAsync()` | | service events | `-=` every handler added with `+=` | | JavaScript objects | `await module.DisposeAsync()` on each `IJSObjectReference` | `ComponentBase` ignores exceptions from **canceled** lifecycle tasks, so a load canceled during disposal does not surface as an error. On Interactive Server, a JavaScript call made after the circuit disconnected fails with `JSDisconnectedException`; disposing JS references there is the JS interop topic's concern, but catching that exception in `DisposeAsync` is standard. ## Timing traps - **Disposal can come first.** `DisposeAsync` may run before an awaited `OnInitializedAsync` or `OnParametersSetAsync` resumes. If that work did not receive the cancellation token, `ComponentBase` still continues to `OnParametersSet{Async}` afterwards, so check a `disposed` flag after awaits that are not cancellable. - **Objects may not exist yet.** Fields assigned in lifecycle methods can still be `null` when disposal runs, so null-check them. - **No UI from disposal.** Calling `StateHasChanged` in `Dispose` or `DisposeAsync` is not supported; the renderer may be tearing down. - **Don't block.** A long `DisposeAsync` holds up the teardown of the component. ## Disposal versus OnAfterRender cleanup Creating something in `OnAfterRenderAsync(firstRender: true)` and releasing it in `DisposeAsync` is the standard pair for browser-side resources. For server-side resources started in `OnInitialized` - timers, subscriptions - the pair is `OnInitialized` and `DisposeAsync`.
- Why does the polling loop above end with an OperationCanceledException that the user never sees?Cancelling `cts` makes the pending `GetAsync` or `WaitForNextTickAsync(cts.Token)` throw `OperationCanceledException`. The loop was started with a discard (`_ = PollAsync()`), so nothing observes that canceled task. For loops whose failures you do want to surface, catch other exceptions inside the loop and pass them to `DispatchExceptionAsync` so an `ErrorBoundary` can show them.
- A component subscribes to a singleton's event in OnInitialized and never unsubscribes. What happens on Interactive Server?The singleton's event keeps a reference to the component's handler, so the component - and what it references from its circuit - cannot be garbage collected after it is removed or the circuit closes. The handler also keeps running for a component that is no longer rendered, and any `StateHasChanged` it requests is wasted or fails. Unsubscribe in `Dispose`/`DisposeAsync`.
- ComponentBase disposes timers and subscriptions automatically when a component is removed.
- If a component implements IDisposable and IAsyncDisposable, Blazor calls both.
- DisposeAsync always runs after OnInitializedAsync has completed.
- Calling StateHasChanged in DisposeAsync is a good way to show a closing message.
- Blazor only disposes components when the whole circuit ends, not when one leaves the page.