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 ?
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: