Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Is it Possible to Iterate GC Heap?

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 ?

like image 698
user160677 Avatar asked Sep 22 '09 19:09

user160677


2 Answers

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.

like image 200
Andrew Hare Avatar answered Nov 05 '22 04:11

Andrew Hare


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.

like image 2
Moshe Levi Avatar answered Nov 05 '22 04:11

Moshe Levi