WPF Memory Leak on XP (CMilChannel, HWND)

这一生的挚爱 提交于 2019-11-27 13:22:29

问题


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"));

回答1:


The fix:

Application.xaml.cs

class MyApp1 : Application
{
   // ...

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


来源:https://stackoverflow.com/questions/1705849/wpf-memory-leak-on-xp-cmilchannel-hwnd

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!