Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to debug .net Garbage Collection?

Is it possible to have a look at all .net objects which are collected upon calling GC.Collect()?

I need to see what objects are still in memory and not reclaimed, so I can find where reclaiming the objects should have done manual, but was forgotten by the programmer.
I don't want to call GC.Collect because someone somewhere forgot to dispose an object which blocks some handles.

like image 414
Sam Avatar asked Feb 17 '09 14:02

Sam


People also ask

How does .NET framework manage garbage collection?

NET's garbage collector manages the allocation and release of memory for your application. Each time you create a new object, the common language runtime allocates memory for the object from the managed heap.

How does C# handle garbage collection?

How GC works? GC works on managed heap, which is nothing but a block of memory to store objects, when garbage collection process is put in motion, it checks for dead objects and the objects which are no longer used, then it compacts the space of live object and tries to free more memory.

Is there garbage collector in C#?

The collector starts claiming objects in the youngest generation. Then it promotes the survivors to the next generation. The C# garbage collection uses three generations in total: Generation 0—This generation holds short-lived objects.


1 Answers

I've found the best way to do this is to use windbg and the SOS (son of strike) extension. It has a rather cryptic command line but it is very powerful. It has the capability to dump the heap and divide it by the GC generational heap. Once you get past the initial learning curve, it's very easy to track what objects are alive in what portion of the heap. Here are a few web sites with examples of using SOS

  • http://blogs.msdn.com/tess/archive/2005/11/25/dumpheap-stat-explained-debugging-net-leaks.aspx
  • http://geekswithblogs.net/.NETonMyMind/archive/2006/03/14/72262.aspx
  • http://dotnetdebug.net/2005/07/04/dumpheap-parameters-and-some-general-information-on-sos-help-system/

EDIT OP asked about the location of sos.dll. It is included with the install of the .Net Framework. It is located at

%WINDIR%\Microsoft.Net\Framework\V2.0.50727\sos.dll

But once you have windbg loaded you don't need the full path. Just us the .loadby method.

.loadby sos mscorwks.dll

It will look for the version of sos in the same directory as the current version of mscorwks (the CLR)

like image 181
JaredPar Avatar answered Oct 03 '22 23:10

JaredPar