WPF Memory Leak By Design

I have just finished debugging a memory leak in our code base. The culprit was a global static command which was rooting all controls ever attached to it, through its CanExecuteChanged event.

Surely controls which attach to this event, detach!?

No. WPF expects the ICommand.CanExecuteChanged event to apply WeakReferences for EventHandlers.
So beware if you use global commands that don’t implement this correctly.

An example of how to implement this is here.


One Reply to “WPF Memory Leak By Design”

  1. I’ve had this problem too, and it’s one of the most enraging gotcha in WPF. There isn’t even a MSDN knowledge base article that I’ve seen that tells you to look out for this, not to mention the MSDN documentation itself, which explain an API that “by design” creates a memory leak, without any warning.

    They simply shouldn’t have released WPF before creating fundamental support for the Weak Event Design Pattern within .NET, rather than leave you to fend yourself and roll your own solution. The fact that they didn’t shows they were just plain irresponsible.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s