Question

Q. Is there a way to find out if an object has any "strong references" to it?


Raymond Chen hinted that a solution might be possible:

You want to know whether the reference count is zero or nonzero. For that, use WeakReference.

Notes

  • i have a "weak reference" to the object (using a WeakReference). If i had a strong reference the answer would immediatly be: "Yes. You have a strong reference to the object."
  • the garbage collector exposes no answers
  • the IsAlive property can only tell you if an object has been collected, or not. Not if there are strong references to it, or not. (An object with no references can be uncollected - the GC just hasn't gotten around to it yet)
  • objects in .NET are not reference counted
  • not all objects have to implmenet the IDisposable interface
  • not all objects are mine

Code Sample

This code sample demonstrates the problems with relying on forcing a garbage collection and the WeakReference's IsAlive property to determine if an object has any outstanding references to it.

WeakReference m_wr = null;

...

for (int i = 0; i < 1000000; i++)
{
   Pig p = new Pig();
   m_wr = new WeakReference(p);
}

...

GC.Collect();
if (m_wr.IsAlive)
   Environment.FailFast("All objects should have been collected by now");
Was it helpful?

Solution

Nope, not without using the debugger API.

As you say, objects aren't reference counted... so the only way of finding out would be to crawl the heap, which normally just happens as part of garbage collection.

Note that even after there are no "normal" strong references, the object could be resurrected as part of finalization anyway - effectively the finalizer queue has a reference to it, if it has a finalizer. Maybe you wouldn't want to include the object as "reference-less" in that situation anyway.

OTHER TIPS

First call GC.Collect() and then check WeakReference.IsAlive. If it is true (i.e., it hasn't been collected after calling GC.Collect) then there is a strong reference somewhere.

You should read Raymond Chen's post about Reference counts from yesterday. After that - you should decide if that's something you really need to do and why. Then come back and tell us why.

Hmm, it seems you've read the post - absorbed minor details and missed the point.


i want to know if it's safe to call Dispose on a database connection.

Read the docs. Dispose calls Close. Close is safe to call as much as you like.

An application can call Close more than one time. No exception is generated.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top