Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get active references to an object

I am looking for a managed/unmanaged API that will allow me to find which objects reference another object and are potentially keeping it from being garbage collected.

Such an API might look like this:

var foo = new Foo();
var bar = new Bar();
bar.Foo = foo;

var references = GC.GetReferencesTo(foo);
// references is an array that contains bar

I know profilers can be used for this but I'd like to make it part of a unit test. Is there a managed or unmanaged API that I could use?

like image 958
Paul Stovell Avatar asked Nov 24 '09 00:11

Paul Stovell


1 Answers

The unmanaged dll SOS (Son Of Strike) provides a means to achieve this, though I do not believe it has significant scripting support, nor does it provide a simple means to achieve this via a single command. You would have to introspect the variable's address, check all gcroots for the variable (which would include the stack obviously) and deal with the remainder.

I would suggest that, if you wish to prove that an object is not referenced, a simpler technique would be to (temporarily) make it finalizeable, ensure it is no longer referenced on the stack of your unit test and then force several garbage collections via GC.Collect() then use GC.WaitForPendingFinalizers().

Your finalize method can set a static boolean flag and then your unit test can assert this is true.

I would question the utility of this without further explanation but this is likely to be the simplest method of proving no dangling references exist in a unit test.

like image 76
ShuggyCoUk Avatar answered Sep 24 '22 14:09

ShuggyCoUk