Component Disposal in Blazor
Developers need to manage the resources used in the application. They need to release unmanaged resources that will help prevent memory leaks. The Blazor provides two implementations for releasing the component. IDisposable and IAsyncDisposable
IDisposable
The following is a small example of the code to illustrate the disposal of components in Blazor. The first step is to implement the IDisposable interface using the @implements directive. The Dispose() method is then used to release the memory.
@page "/sample" @implements IDisposable @code { Movie movieObj; private void CollectValues() { movieObj = new Movie(); ... ... ... } public void Dispose() { movieObj?.Dispose(); } }
If only one object requires disposal, you can use the lambda expression.
public void Dispose() => movieObj?.Dispose();
IAsyncDisposable
You can use IAsyncDisposable.DisposeAsync for asynchronous disposal. The following is an example of IAsyncDisposable. The code will be similar to the synchronous disposal method. In the code first IAsyncDisposable is implemented using @implements directive. The DisposeAsync() method is then used to release the memory.
@page "/sample" @implements IAsyncDisposable @code { Movie movieObj; string str; private void CollectValues() { movieObj = new Movie(); ... ... ... } public async ValueTask DisposeAsync() { if (movieObj != null) { await movieObj.DisposeAsync(); } } }
Note:
It is not necessary to assign null values to the removed object.
I hope this helps you. Keep coding.
Comments
Post a Comment