0

There are some heavy JS objects I would like to clean up using the dispose method. I use IJSObjectReference to call JS code.

The code:

public partial class BlazorComponent : IAsyncDisposable, IDisposable
{
    private bool _isDisposed;
    private IJSObjectReference? _jsModule;

    // ...

    public async ValueTask DisposeAsync()
    {
        await DisposeAsync(true);
        GC.SuppressFinalize(this);
    }

    public void Dispose()
    {
        DisposeAsync(true); // Won't be awaited
        GC.SuppressFinalize(this);
    }

    private async ValueTask DisposeAsync(bool disposing)
    {
        if (_isDisposed)
            return;

        if (_jsModule is not null)
            await _jsModule.InvokeVoidAsync("deleteHeavyObject");

        if (disposing)
        {
            if (_jsModule is not null)
                await _jsModule.DisposeAsync();
        }

        _isDisposed = true;
    }

    ~BlazorComponent()
    {
        DisposeAsync(false); // Won't be awaited
    }
}

The IJSObjectReference only implements IAsyncDisposable and you can only call JS methods via async methods.

What is the best practice to deal with this situation?

I could do DisposeAsync(...).AsTask().Wait() or I could just not implement IDispose and the deconstructor because it looks like in Blazor Dispose/DisposeAsync gets called regardless of the GC?

4
  • 1
    Why are you implementing a finalizer and IDisposable at all? Commented Jan 16, 2022 at 1:17
  • Sorry, I don't understand your question. I need to dispose the JS object and I followed the best practices for the dispose pattern. I don't know if it's needed tho, as I mentioned in the post. I couldn't find any resources on how the GC in Balzor WASM works (or if there even is one). The most helpful resource I could find is this Component life where it looks like a finalizer isn't needed because Blazor calls the IAsyncDisposable.DisposeAsync implementation regardless of any GC. Commented Jan 16, 2022 at 3:42
  • The first rule of finalizers is "don't implement it unless you need to" (link is to my blog). In this case, since your type contains a component that only implements IAsyncDisposable, then your type should only implement IAsyncDisposable. Then you don't have any problems. Commented Jan 17, 2022 at 0:45
  • See here for related issue and solutions. Commented Dec 27, 2022 at 23:23

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.