How do you handle component disposal for long-lived resources, and how do IDisposable and IAsyncDisposable work in the context of a Blazor circuit?
Last updated
Add
@implements IDisposableorIAsyncDisposable. Blazor calls it when the component is removed or the circuit (the per-user server connection) ends.Use
Disposefor quick cleanup (unsubscribe events, timers, cancel tokens) andDisposeAsyncfor awaited cleanup likeIJSObjectReference. Undisposed subscriptions leak memory in long-lived Server circuits.JS may be gone during teardown, so guard interop in
DisposeAsyncand catchJSDisconnectedException.
- https://blazor-university.com/components/component-lifecycles/
- https://learn.microsoft.com/en-us/aspnet/core/blazor/components/synchronization-context?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/blazor/components/component-disposal?view=aspnetcore-10.0
- https://blazor-university.com/javascript-interop/calling-dotnet-from-javascript/lifetimes-and-memory-leaks/
- https://learn.microsoft.com/en-us/aspnet/core/blazor/fundamentals/navigation?view=aspnetcore-10.0
- https://github.com/dotnet/aspnetcore/issues/64847
- https://learn.microsoft.com/en-us/aspnet/core/blazor/fundamentals/handle-errors?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/blazor/javascript-interoperability/call-javascript-from-dotnet?view=aspnetcore-10.0