Mehdiway
Mehdiway

Reputation: 10656

Dispose not called on child components in Blazor

I have a parent component that implements IDisposable, where I have a child component called MyGrid. Now MyGrid extends Syncfusion's SfGrid which itself implements IDisposable. When I close the parent component its Dispose method is called but Dispose inside MyGrid isn't called. Is it normal ? I thought Dispose had like a chain effect. Should I explicitly call Dispose on MyGrid (after getting a reference to it)?

Parent.razor :

<MyGrid ... />

MyGrid.cs :

public class MyGrid<T> : SfGrid<T>
{
    ...

    public override async void Dispose()
    {
       await PersistDataAsync();
    }
}

Upvotes: 0

Views: 72

Answers (1)

Farzad M.
Farzad M.

Reputation: 341

I think you need to use DisposeAsync. It was introduced in dotnet8. Using it can be a little tricky:

  • if your MyGrid is a sealed component (you do not need to write other components which inherit from MyGrid), the task is easy:
public sealed class MyGrid<T> : SfGrid<T>, IAsyncDisposable
{
...
    public ValueTask DisposeAsync() => PersistDataAsync();
}
  • if your MyGrid is not a sealed class, there are some complexities implementing it.

I strongly suggest you to read Implement a DisposeAsync method.

P.S. I completely agree with Henk. Persisting data in Dispose is not considered best practice. Exercise caution when doing that.

Upvotes: 0

Related Questions