views:

158

answers:

3

Is there a way I can know who holds a reference to an object?

I see that my object is not finalized by the d'tor after I call GC.Collect.

+4  A: 

There is no way to do this effectively in code. The best way to track down leaks of this sort is to use a tool like WinDbg. The SOS extension has several commands which are specifically designed to help track down memory leaks.

Rico did a thorough blog entry on the subject:

JaredPar
+2  A: 

You ought to call GC.WaitForPendingFinalizers after GC.Collect to allow the garbage collector to clear the freachable queue. Since the GC runs in a different thread it is possible that your application has moved on while the GC is trying to finalize any objects that require finalization. By calling GC.WaitForPendingFinalizers you are forcing your current thread to wait until the GC has finished clearing the freachable queue (the queue of items that require finalization) before resuming execution.

That being said however, I agree with Joel Coehoorn's comment - the GC works best when you leave it alone.

Andrew Hare
+2  A: 

In addition to Windbg, you could use a .net profiler. I've done it both ways -- the profile won't tell you anything that Windbg can't, but a good profiler is a little more friendly.

Windbg In addition to the link from JaredPar, Tess Ferrandez has some great articles on using Windbg with .net. Here's a a memory leak article: http://blogs.msdn.com/tess/archive/2006/01/23/516139.aspx

Profiler: I have had great luck with SciTech's profiler (I'm not affiliated in any way, great tool, though): http://memprofiler.com/

They have some great how-to videos on their site as well.

JMarsch