Sunday, October 28, 2007

Care about Event Memory Leaks with Delegate.GetInvocationList()

Subscribed events are one of the most common reasons of memory leaks in .Net. This means that if you have an object that has an event

and there are other object that are subscribed to that event, the original object won't be properly disposed until all events are unsubscribed since

an event is a strong reference.

 ....

public partial class MyForm : Form
{
public event EventHandler OnDoMyFormThing;

public MyForm()
{
InitializeComponent();
}

private void button1_OnClick
{
MessageBox.Show(
"Test of OnDoMyFormThing event"
);
OnDoMyFormThing(this, new EventArgs());
}

protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
foreach (EventHandler eventDelegate
in
OnDoMyFormThing.GetInvocationList())
OnDoMyFormThing -= eventDelegate;
components.Dispose();
}
base.Dispose(disposing);
}
}



 


To full  article click here

No comments: