views:

698

answers:

2

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"));
+2  A: 

The fix:

Application.xaml.cs

class MyApp1 : Application
{
   // ...

   public Application()
   {
       new HwndSource(new HwndSourceParameters());
   }
   // ...
}
vanja.
A: 

Guys, thanks for this, been battling with a memory leak on and off for weeks, you have solved my problem!

JC