Associating an object with another object to clear the GC

Is there a way to associate an instance of an object (object A) with a second object (object B) in a generalized way, so that when B is assembled, A becomes acceptable for collection? The same behavior that could happen if B had an instance variable pointing to A, but without explicitly changing the definition of class B and being able to do it dynamically?

The same effect could be made using the Funky-style Component.Disposed event, but I don't want to make B one-time

EDIT

I basically create a cache of objects that are associated with one "root" object, and I do not want the cache to be static, as there can be many root objects using different caches, so a lot of memory will be used when the root object is no longer be used, but cached objects still exist.

So, I want the collection of cached objects to be associated with each "root" object without changing the definition of the root object. Similar metadata is an additional reference to objects attached to each instance of the root object. Thus, each collection will be assembled during the assembly of the root object, and not freeze, as if they were used, if a static cache was used.

+4
source share
2 answers

Short answer: Probably not. Can you explain more of what you are trying to do? There, the chance of a WeakReference may be what you need.

+1
source
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 the RelatedReference each time you use B like this:

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

Source: https://habr.com/ru/post/1304883/


All Articles