Remember to unhook those event handlers!

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()
  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);



  1. Pingback: GeekTieGuy » Inside the HP TouchSmart PC software: HP SmartCenter - Part 2

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.