4

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: 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"));
Community
  • 1
  • 1
vanja.
  • 2,532
  • 3
  • 23
  • 39
  • I don't have a definite answer for you, but here is a fact that may help: I have discovered that just doing a "new HwndSource(...)" and nothing else (as you show above) is enough to cause WPF to call RegisterClassEx to do the subclassing (what Win32 calls subclassing; not what we call "subclassing" in .NET), and CreateWindowEx to create a new hWnd. This would lead me to believe that the line you wrote above is all that is necessary to overcome the particular leak you linked to, so the problem is probably elsewhere. Some of the other techniques in the links may help. – Ray Burns Nov 10 '09 at 21:43
  • Yes, I noticed that simply creating a new HwndSource was beneficial, but that made a tiny new blank window. I think hiding it might be as bad as not having it at all. – vanja. Nov 11 '09 at 02:09
  • By not setting the window title in HwndSourceParameters, the window stops appearing and fixes the memory leak problem. – vanja. Nov 12 '09 at 07:23

1 Answers1

6

The fix:

Application.xaml.cs

class MyApp1 : Application
{
   // ...

   public Application()
   {
       new HwndSource(new HwndSourceParameters());
   }
   // ...
}
vanja.
  • 2,532
  • 3
  • 23
  • 39