robburke.NET
© 2009 Robert Burke
All Rights Reserved.

I can’t resist linking to a superb article in the WPF Performance blog on finding memory leaks in WPF-based applications.

Particularly interesting is the section pertaining to Event Handler-based leaks. Here’s the brief summary, from the article:

In general, if you do this:

Foo.SomeEvent += new EventHandler(Bar.SomeMethod)

Then when you done using Bar, but you are still using Foo then Bar will still remain alive as well. Not what you might have expected.

Detatching the Event Handler from Foo.SomeEvent is not always practical. The proposed alternate is the “Weak Delegates” solution – a construct which isn’t natively supported by the CLR. A detailed discussion of how to simulate weak delegates is at Greg Schechter’s blog.

I got burned yesterday by not catching the need for the proverbial Weak Delegate, and I’ve been burned before by not using this technique when attaching event handlers in WPF (and particularly XNA and Managed DirectX) apps.

I’d classify both articles as “advanced,” and the solution as laborious, but if you want to write stable and long-running apps on the CLR (and who doesn’t? :) ), this issue is going to jump up and bite you in the proverbials at some point.

Possibly Related Articles

  1. “Mate, this is the Future”
  2. End-to-End Custom WPF Shader Example
  3. O# at the Movies

Trackback URI | Comments RSS

Leave a Comment