views:

36

answers:

3

I have a Windows.Forms app with a ListBox populated with Account objects. When the user selects an Account from the list I attach an EventHandler responsible for updating the selected Account transactions in the event that there's any new ones while the user is looking.

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    var selected = listBox1.SelectedItem as Account;
    if (selected != null)
    {
        UpdateTransactions(selected);
        selected.OnNewTransaction += (s, a) => UpdateTransactions(selected);
    }
}

Then my question is as follows; Is this eventhandler automatically disposed of as soon as the user selects another Account from the list and the selected account goes out of scope ? Or does it continue to linger on, and then if the user selects the same account again is assigned another handler thereby creating a memoryleak ?

A: 

You need to detach it manually

Anton Setiawan
+3  A: 

It remains, so each time the user selects the same account again it is assigned again.

In order to detach the event again you should tweak the way that you attach the event, to keep a reference to it:

EventHandlerType handler = (s, a) => UpdateTransactions(selected);
selected.OnNewTransaction += handler;

// When you want to remove the handler do this (make sure you "store" handler somewhere)
selected.OnNewTransaction -= handler;
Kragen
Thanks for the quick answer :)
Frank
+1  A: 

The event handlers are only candidates for garbage collection when the Account objects are themselfs collected for garbage. So yes, the handles continue to exist unless you don't explicitlly detach them from Account objects, and yes, the event will contain all the handles you attach to it.

bruno conde