开发者

Associating an object with another object for GC clearup

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 开发者_JS百科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.


Short answer: Probably not. Can you explain more of what you're trying to do? There's a chance WeakReference might be what you need.


public class RelatedReference<A, B>
{
    private A a;
    private B b;

    public B Referent
    {
        get {return b;}
    }

    public RelatedReference(A a, B b)
    {
        this.a = a; 
        this.b = b;
    }
}

Then just use RelatedReference every where you would use B like so:

    var Bref = new RelatedReference<A, B>(new A(), new B());
    Bref.Referent.Foo();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜