Desmond Ma
Desmond Ma

Reputation: 93

Blazor call Dispose when components implements IDisposible

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?

Upvotes: 9

Views: 24045

Answers (2)

Henk Holterman
Henk Holterman

Reputation: 273464

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 an @if(...) { ... }

Upvotes: 9

meziantou
meziantou

Reputation: 21347

Blazor calls Dispose or DisposeAsync if you implement IDisposable or IAsyncDisposable

https://learn.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.

Upvotes: 12

Related Questions