Geeks With Blogs
Adrian Hara Working through the .NET maze
Profiling some memory problems in the latest project i worked on we found out something rather disturbing:
   a WPF UserControl/Window uses a DispatcherTimer (declared as a private member in the UserControl's code-behind)
   the event handler for the timer's Tick event is also declared in the UserControl's code-behind
   that UserControl/Window is shown/opened by a parent
WHEN the UserControl/Window is dismissed WITHOUT stopping the Timer or unsubscribing from its Tick event
THEN you have a memory leak.

Basically what we were doing was opening/showing some Windows/UserControls which would then get dismissed at some point. Unfortunately they never got collected. We traced it down to the DispatcherTimer and actually the Dispatcher for the thread itself. What happens is when you Start() the DispatcherTimer it adds itself to a list of timers that the current Dispatcher is keeping. If you never stop it then it never gets removed from that list, and since the Dispatcher is rooted, whoever handles the timer's Tick is also rooted, so it never gets collected.

So the lesson is to always Stop() the DispatcherTimer or unsubscribe from its Tick event. Either way will get rid of the rooted path to your control and will allow the garbage collector to reclaim it. Another option is to use weak events. This might seem like overkill, but the fact is that, depending on your design, you might not KNOW when it's a good time to either Stop() the timer or unsubscribe from its Tick event. You can read about weak events (which are implemented already in WPF) in the following links:

Basic idea:

WPF implementation idea:

How to use them:!FD9A0F1F8DD06954!471.entry?wa=wsignin1.0&sa=479373232

A nice trick to simplify your amount of work:

Posted on Thursday, November 5, 2009 4:31 AM | Back to top

Comments on this post: Nasty DispatcherTimer memory leak

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © Adrian Hara | Powered by: