Frank
Frank

Reputation: 483

Garbagecollection of eventhandlers

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 ?

Upvotes: 3

Views: 75

Answers (3)

bruno conde
bruno conde

Reputation: 48255

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.

Upvotes: 1

Justin
Justin

Reputation: 86789

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;

Upvotes: 3

Anton Setiawan
Anton Setiawan

Reputation: 899

You need to detach it manually

Upvotes: 0

Related Questions