none
Determine how an object is referenced/rooted RRS feed

  • Question

  • Hi everyone,

    I have a query which might be something that cannot be done but thought I would ask. Is it possible to determine how an object is rooted to the GC handle (or whatever it is called), that is how it is attached to an object which is still alive so that it does not get garbage collected.

    As an example of why I ask. I have a class that acts as a cache for objects that may be requested at various times in an app. Periodically I want the cache to 'clean' itself, that is to remove objects which are no longer referenced by anything other than the cache. I can see that when an object gets requested that is not already cached, the cache would load it, add it to the cache then return it. However when the requestor is done with the object and no longer references the cache will still hold a reference, thus the object will never be GCed. Is it possible for the cache to be able to determine whether any object in its list is referenced by anything other than the cache?

    Regards,

    Mark.
    Wednesday, June 18, 2008 11:54 PM

Answers

  • > Is it possible for the cache to be able to determine whether any object in its list is referenced by anything other than the cache?

    Yes, so long as all of the references that the cache has to the objects are done using the WeakReference class.  A WeakReference is a reference that does not prevent its target object from being garbage collected.

    http://msdn.microsoft.com/en-us/library/system.weakreference.aspx

    When you are ready to clean up the cache, you can scan through all of the WeakReferences in your cache.  If WeakReference.IsAlive = false, the GC has collected the target object, so you can drop the WeakReference from the cache.
    • Marked as answer by spanky4_3 Thursday, June 19, 2008 3:40 AM
    Thursday, June 19, 2008 3:02 AM

All replies

  • > Is it possible for the cache to be able to determine whether any object in its list is referenced by anything other than the cache?

    Yes, so long as all of the references that the cache has to the objects are done using the WeakReference class.  A WeakReference is a reference that does not prevent its target object from being garbage collected.

    http://msdn.microsoft.com/en-us/library/system.weakreference.aspx

    When you are ready to clean up the cache, you can scan through all of the WeakReferences in your cache.  If WeakReference.IsAlive = false, the GC has collected the target object, so you can drop the WeakReference from the cache.
    • Marked as answer by spanky4_3 Thursday, June 19, 2008 3:40 AM
    Thursday, June 19, 2008 3:02 AM
  • Hi BinaryCoder,

    Thanks for the response. WeakReference looks like it will work perfectly! Thanks for pointing me in the right direction.

    Regards,

    Mark.
    Thursday, June 19, 2008 3:40 AM