views:

329

answers:

4

Is it possible to access the managed heap in a .NET application and e.g. enumerate the objects that are currently allocated there?

I know there are various tools out there that allow you to do that, but I would rather do this myself from code so that I can use it in automated tests, like for checking if everything is disposed and cleaned up after closing a form.

+1  A: 

You can use the CLR Profiler to see this information:

http://www.microsoft.com/downloads/details.aspx?familyid=86ce6052-d7f4-4aeb-9b7a-94635beebdda&displaylang=en

Keltex
I know, but that is not what I need. I want to do this within my own C# application, not with some external interactive tool. So basically I want to know how to do myself (part of) what CLR Profiler does.
Timo
+1  A: 

The only way, besides using a profiler, is with WinDbg and with the SOS extension loaded.

IIRC, you call !EEHeap.

leppie
Well, if all those profilers can do it, then I guess there must be a way ... so I want to know how a profiler does this :-)
Timo
Have a look at the .NET Profiling api.
leppie
+1  A: 

http://www.softprodigy.net/ has a profiler with the source code available.

Robert Harvey
+1  A: 

Profilers (using the Profiling API) are 'external' components (not quite COM) in the sense that they get loaded by the CLR and has various options of getting called on any method enter/leave/tail call in the managed code (and lots of other stuff as well). They are written in unmanaged code.

AFAIK there is no way to get this info internally without calling out to a profiler/debugger that monitors the CLR. Also remember that you can not always get this kind of information as much of it only exists after your code has finished execution (many Dispose() calls, finalization and such).

S.Skov