Search code examples
c#eventsgarbage-collectionblazorblazor-webassembly

Do I always need to unsubscribe events of nested class instances in Blazor WASM razor page?


I have a ClosestEvents.razor page with this code behind:

public partial class ClosestEvents: IDisposable
{
    private MyEventSource Source;

    protected override void OnInitialized()
    {
        Source = new MyEventSource();
        Source.OnDataUpdated += StateHasChanged;
    }

    public void Dispose()
    {
        if(Source != null)
            Source.OnDataUpdated -= StateHasChanged;
    }
}

Do I always have to manually unsubscribe and as a consequence implement a Dispose method? As I know not unsubscribing can cause memory will not collected by GC but I guess in this case subscriber and source both will be available for GC. Can I not usbubscribe in this case? Will GC handle this well? Something like this:

public partial class ClosestEvents
{
    private MyEventSource Source;

    protected override void OnInitialized()
    {
        Source = new MyEventSource();
        Source.OnDataUpdated += StateHasChanged;
    }
}

Solution

  • Will GC handle this well?

    Yes.

    Source.OnDataUpdated += StateHasChanged; creates a reference from the Source element to the Component this is in.

    But because it is declared as private MyEventSource Source; the Source has the same lifetime (GC reachability) as the owner.

    You do not have to unsubscribe events like this. And I wouldn't, it's clutter.