Associating an object with another object for GC clearup

Posted by thecoop on Stack Overflow See other posts from Stack Overflow or by thecoop
Published on 2010-03-23T13:58:02Z Indexed on 2010/03/23 14:53 UTC
Read the original article Hit count: 303

Filed under:
|
|

Is there any way of associating an object instance (object A) with a second object (object B) in a generalised way, so that when B gets collected A becomes eligable for collection? The same behaviour that would happen if B had an instance variable pointing to A, but without explicitly changing the class definition of B, and being able to do this in a dynamic way?

The same sort of effect could be done by using the Component.Disposed event in a funky way, but I don't want to make B disposable

EDIT

I'm basically creating a cache of objects that are associated with a single 'root' object, and I don't want the cache to be static, as there can be lots of root objects using different caches, so lots of memory will be used up when a root object is no longer used but the cached objects are still around.

So, I want a collection of cached objects to be associated with each 'root' object, without changing the root object definition. Sort of like metadata of an extra object reference attached to each root object instance. That way, each collection will get collected when the root object is collected, and not hang around like they would if a static cache was used.

© Stack Overflow or respective owner

Related posts about c#

Related posts about garbage-collection