C# - Is it Possible to Iterate GC Heap?

2019-06-21 18:56发布

问题:

I'm not sure whether the following questions are valid.To educate myself i am just asking.

( 1 ) Can I programmatically iterate the GC Heap of all generations ?

( 2 ) Is it possible to watch how does the GC operate on my assembly by launching a thread ?

回答1:

The answers to you questions are:

  1. Unfortunately no, you cannot. The CLR's garbage collector works in a mark, sweep, compact pattern so in between runs there is no information about the heap (other than size of the heap or the current generation of a specific type instance) that would allow you to iterate all objects in it.

  2. The best way to monitor the GC is to use perfmon and watch (or log) the CLR memory counters.



回答2:

I was searching the internet a while ago for an answer to the same question but I didn't find any way to iterate the GC heap programically.

If you just need to watch this information for debugging purposes you can launch WinDbg and load the SOS extension. than you can use the !dumpheap extension command to see exactly what objects are on the GC heap. you can also use dotTrace's memory profiling mode if you have it.