Search code examples
c#winformsevent-handlingmvp

WinForms: Should I always unregister event callbacks?


I have code that looks like this:

class MyPresenter
{
    public MyPresenter(IViewFactory viewFactory, ...)
    {
        _view = viewFactory.GetMyView();
        _view.OkClicked += OnOkClicked;
        _view.CancelClicked += OnCancelClicked;
        ...
    }


    public ShowView()
    {
        ...
        _view.ShowDialog();  
    }
}

Is it necessary to put a -= somewhere? And if so, does it make sense to put it in the finalizer?


Solution

  • it is important to unregister from an event when the lifetime of the subscribing object is assumed to be shorter than the lifetime of the object firing the event.

    One good example is App.Idle. App lives throughout the lifetime of your Windows Forms App. If you register on this event, App now has a reference to said object, that is, if you don't unregister, your object assumes the same lifetime as App.

    I would like to point you to my post on Windows.Forms "memory leaks". Note these do not prove there is anything wrong with the Garbage Collector, but there are corner cases, where unmanaged code isn't far away, or when you have lifetime issues surrounding events.