Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unregistering all events to release memory

Tags:

c#

events

I have a program which allows the editing of product information. I noticed that it was not releasing memory after closing the editing forms. After some research I stumbled upon this question which mentions that the problem may be that it is hanging on to event subscriptions.

That made sense to me because this form has about 100+ controls on it, many of which are custom with custom events which are subscribed to by their parent controls. This creates a pretty large hierarchy of event subscriptions. So I looked for a way to release these and found this which allows you to unsubscribe from that event.

The problem is, I have a ton of subscriptions. Do I really have to manually unsubscribe from each event one by one on form close, or is there at least a way to release them in one fell swoop, or loop through them?

like image 835
Nick Avatar asked May 03 '13 15:05

Nick


2 Answers

Remember this: The object on the LEFT of the += keeps alive the object containing the method on the RIGHT of the +=. That is, the object that raises the event keeps alive the object that handles the event, even if the object (such as a form) that handles the event is disposed.

So the thing you need to ensure is that all the event-raisers have gone away.

However, if all the event-raisers happen to be controls in the same Form class that subscribes to those events, you will not need to manually unhook all the event handlers when the form is closed.

This is because the controls that raise the events to which to form has subscribed have the same lifetime as the form itself.

You only need to worry if you subscribe to events raised by an object that has a longer lifetime than the object that is subscribing. Then the subscribing object (the form) would need to unsubscribe when it (the form) is disposed.

like image 51
Matthew Watson Avatar answered Oct 30 '22 12:10

Matthew Watson


It depends on how long your form and its events will be living.

However, you can loop through your controls within the form, releasing the events. If you remove a nonexisting event accidentally - don't worry, it won't throw an exception.

For example, this is how to get rid of all your TextBox.KeyDown-Events:

  private void frm_FormClosed(object sender, FormClosedEventArgs e)
    {
    foreach (Control tb in this.Controls)
    {
        if (tb is TextBox)
        {
            TextBox tb1 = (TextBox)tb;
            tb1.KeyDown -= TextBox_KeyDown;
        }
    }
like image 36
Fabian Bigler Avatar answered Oct 30 '22 13:10

Fabian Bigler