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.
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");
Objects are an example of a reference type. In the above example, both variables a and b will point to the same student object in memory.
Of course you can have objects reference each other. You could simply pass the this pointer in both objects to each other, which is perfectly valid.
A link to an object. Object references can be used exactly like the linked objects. The concept of object references becomes clear when assigning the same object to more than one property.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With