Detecting memory leak in mixed environment(Managed

2020-02-07 06:57发布

问题:

I've an application written in VC++ MFC 6.0. Recently got upgraded to .NET 3.5 by compiling in vs2008 and added some WPF applications to it by using managed and unmanaged environment. Basically hosting WPF on win32 window. If I just open a WPF app window, memory keeps going up like 1KB/10 secs. I've tried using .NET Memory profiler & Ants memory profiler. But both are not helping me in detecting the leaks!! I've removed all the WPF controls from the hosted WPF application. It just contains a page having just a frame. But still the leak happens!! Would some one please help me what could cause the application memory go up?

回答1:

First, you should determine whether you have a managed memory leak or a native memory leak:

Use these PerfMon counters to do that:

  1. Process/Private Bytes,
  2. .NET CLR Memory/# Bytes in All Heaps,
  3. .NET CLR LocksAndThreads/# of current logical Threads.

If 1 is increasing, but 2 remains stable, you have a native memory leak. If 1 AND 2 are increasing, you have a managed memory leak.

If 3 is increasing unexpectedly, thread stacks are leaking.

If you have found a managed memory leak, .NET memory profiler tools like Ants, YourKit, etc. should help. Since they did not help in your case, you probably have a native leak.

Important: make sure to invoke the garbage collector manually before looking at the memory consumption. If there is not enough memory pressure, the GC will not run and your process' memory increases (which is not a leak in this particular case.) Invoke GC like this:

GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();


回答2:

This article describes some common causes of memory problems with WPF - may be worth taking a read:

http://www.red-gate.com/products/dotnet-development/ants-memory-profiler/learning-memory-management/WPF-Silverlight-pitfalls

Regarding your attempts to find the leak with memory profilers, try the following with ANTS:

1) Take two snapshots a minute or two apart (the profiler automatically runs a garbage collection prior to taking the snapshot each time).

2) Ensure the baseline snapshot is set to snapshot 1 and the last snapshot is set to snapshot 2.

3) Go to the class list.

4) Under 'Basic filters' select 'From current snapshot show only new objects'.

5) Highlight the largest class then go to the instance list.

6) For one of the instance, open the instance retention graph which shows the chains of reference holding that instance in memory.

7) With a bit of luck, you'll see an object holding onto something it shouldn't which you can then fix. If not, repeat steps 5 & 6 but selecting different classes / instances.



回答3:

Well, after some soul searching, found out that the leak is actually due to a bug in the framework. Read this for more http://social.msdn.microsoft.com/Forums/zh/wpf/thread/5b9ae245-9067-4ca4-b846-180db9f7bde5