How to dispose delegate in blazor or c#

55 Views Asked by At

Below I have attached my blazor code.

private delegate Task keyActionDelegate(KeyboardEventArgs e);
private KeyActionDelegate _keyActionDelegate;

protected override async Task OnParametersSetAsync()
{
    await base.OnParametersSetAsync();
    _keyActionDelegate = new KeyActionDelegate(keyActionHandler);
    Attributes = BaseUtils.UpdateDictionary("onkeydown", _keyActionDelegate, Attributes);
}

internal async override void ComponentDispose()
{
    base.ComponentDispose();
    _keyActionDelegate = null;
}

A memory leak has occurred due to keyActionDelegate.

I have tried setting the null value to the _keyActionDelegate variable in the ComponentDispose() method, but still a memory leak has occurred. Is there any other way to avoid memory leaks?

1

There are 1 best solutions below

3
Henk Holterman On
protected override async Task OnParametersSetAsync()
{
    _keyActionDelegate = keyActionHandler;  // shorter syntax

    // this is the leak
    Attributes = BaseUtils.UpdateDictionary("onkeydown", _keyActionDelegate, Attributes);
}

internal async override void ComponentDispose()
{
    base.ComponentDispose();
    _keyActionDelegate = null;  // doesn't help
   
    // you need something like this
    BaseUtils.RemoveFromDictionary("onkeydown", _keyActionDelegate);
}