Live Chat Icon For mobile
Live Chat Icon

How can I avoid memory leaks when using JSInterop call?

Platform: Blazor| Category: JavaScript Interop

To avoid memory leaks, dispose the DotNetObjectReference instance created by a component properly and allow proper garbage collection. The DotNetObjectReference instance should be disposed either at component side or JavaScript side.

Use the following patterns to dispose DotNetObjectReference at the component level.

  1. Implement IDisposable interface in the component.
  2. Add Dispose method and dispose DotNetObjectReference object inside the Dispose method.
@implements IDisposable
@inject IJSRuntime jsRuntime
 
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
 
@code { 
 
    DotNetObjectReference<HelloClass> dotNetObject { get; set; }
 
    protected override void OnInitialized()
    {
        dotNetObject = DotNetObjectReference.Create<HelloClass>(new HelloClass());
    }
 
    async Task IncrementCount()
    {
        await jsRuntime.InvokeVoidAsync("MyJavaScriptFunction", new object[] { dotNetObject });
    }
 
    void IDisposable.Dispose()
    {
        dotNetObject?.Dispose();
    }
}
 
@code{
 
    public class HelloClass
    {
        [JSInvokable]
        public void CustomMethod() { }
    }
}

When a component doesn’t dispose the DotNetObjectReference instance, it should be disposed at the JavaScript side as follows.

window.MyJavaScriptFunction = function (dotnetRef) {
    dotnetRef.dispose();
}

Share with

Share on twitter
Share on facebook
Share on linkedin

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.