WPF Memory Leak on XP (CMilChannel, HWND)

Posted by vanja. on Stack Overflow See other posts from Stack Overflow or by vanja.
Published on 2009-11-10T05:39:12Z Indexed on 2010/04/01 8:53 UTC
Read the original article Hit count: 623

My WPF application leaks memory at about 4kb/s. The memory usage in Task Manager climbs constantly until the application crashes with an "Out of Memory" exception.

By doing my own research I have found that the problem is discussed here: http://stackoverflow.com/questions/801589/track-down-memory-leak-in-wpf and #8 here: http://blogs.msdn.com/jgoldb/archive/2008/02/04/finding-memory-leaks-in-wpf-based-applications.aspx

The problem described is: This is a leak in WPF present in versions of the framework up to and including .NET 3.5 SP1. This occurs because of the way WPF selects which HWND to use to send messages from the render thread to the UI thread. This sample destroys the first HWND created and starts an animation in a new Window. This causes messages sent from the render thread to pile up without being processed, effectively leaking memory.

The solution offered is: The workaround is to create a new HwndSource first thing in your App class constructor. This MUST be created before any other HWND is created by WPF. Simply by creating this HwndSource, WPF will use this to send messages from the render thread to the UI thread. This assures all messages will be processed, and that none will leak.

But I don't understand the solution! I have a subclass of Application that I am using and I have tried creating a window in that constructor but that has not solved the problem.

Following the instructions given literally, it looks like I just need to add this to my Application constructor:

new HwndSource(new HwndSourceParameters("MyApplication"));

© Stack Overflow or respective owner

Related posts about wpf

Related posts about memory-leaks