Q:

How can I avoid memory leaks when using JSInterop call in blazor app?

0

This code will help you to understand how to avoid memory leaks when using JSInterop call.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

Implement IDisposable interface in the component.
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 of the DotNetObjectReference instance, should be disposed at the JavaScript side as follows.

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now