Home > Software design >  Blazor call Dispose when components implements IDisposible
Blazor call Dispose when components implements IDisposible

Time:10-21

I've done some reading about Blazor component life cycles and noticed that IDisposible can be used to free up memory. To my understanding about IDisposable's Dispose method, it is not guaranteed to be called unless it is manually invoked or called by the garbage collector.

Given that a Blazor component has implemented IDispose, does the Dispose method get forcibly called as soon as the component is removed from the UI?

CodePudding user response:

Blazor calls Dispose or DisposeAsync if you implement IDisposable or IAsyncDisposable

https://docs.microsoft.com/en-us/aspnet/core/blazor/components/lifecycle?view=aspnetcore-5.0#component-disposal-with-idisposable-and-iasyncdisposable-1

If a component implements IDisposable, IAsyncDisposable, or both, the framework calls for unmanaged resource disposal when the component is removed from the UI. Disposal can occur at any time, including during component initialization.

CodePudding user response:

that IDisposible can be used to free up memory

That is not the right way to look at it. Dispose() is for freeing resources, not memory.
You will only need this when your Component contains (managed or unmanaged) resources. For example a Timer or a DbContext.

does the Dispose method get forcibly called as soon as the component is removed from the UI?

Yes. Normally I would use that for a page but it also works for a component that is removed by for example a @if(...) { ... }

  • Related