Remember to unhook those event handlers!

August 7, 2006 3:13 pm

I thought I’d make my first post not just a “hello out there”, but something that’s marginally useful to some people. 

If you’re writing a Windows Presentation Foundation app that has just a little bit of complexity to it, you may do things like hook up UI Elements to event handlers. This could be for navigation, reacting to data changes, timers etc.

An important thing to remember is to unhoook those event handlers when your UI Element is unloaded. Otherwise the event handler hangs on to the visual tree and the garbage collector will not let go of it. This results in memory consumption “problems”, which is a nice word for a “managed memory leak”.

So if you do something like this:

public MyElement()
{
  InitializeComponent();
  Loaded += new EventHandler(OnLoaded);
}

public void OnLoaded(object sender, EventArgs e)
{
  myTimer.Tick += new EventHandler(OnTick);
}

Don’t forget to also hook the Unloaded event and do this in it:

public void Unloaded(object sender, EventArgs e)
{
  myTimer.Tick -= new EventHandler(OnTick);
}

 

One Response to “Remember to unhook those event handlers!”

[…] issues we had run into. That’s when I learned that there is such a thing as a “managed memory leak“, which can be introduced in WPF without the programmer necessarily realizing it. Towards the […]

Care to comment?

%d bloggers like this: