Suppose I have 2 classes, Foo and Bar. Foo does not have (and cannot have) a relation to Bar.
However, I want a bar instance to stay alive, as long as it\'s foo instance
Can you create a public object field called BarReference in type Foo?
Someone outside of Foo should set the proper instance of Bar to this property.
As long as there is a reference to the bar instance it won't be GCed AND using object Foo doesn't know anything about Bar type.
Have a look at the ConditionalWeakTable Class.
Enables compilers to dynamically attach object fields to managed objects.
It's essentially a dictionary where both the key and the value are a WeakReference, and the value is kept alive as long as the key is alive.
For example, you can define a
ConditionalWeakTable<Foo, Bar> table
and add a Foo/Bar pair. The Bar instance is kept alive as long as a reference to the Foo instance exists. You can find the Bar instance for the Foo instance by looking at the table.
Bar can only not be finalized if SOMETHING has a reference to it. Just have Foo tell that thing when it can let go of Bar.
It's difficult to give suggestions without knowing exactly what you're trying to achieve, or what you mean by "alive". Normally you shouldn't need to worry about lifetime of managed objects: they "die" naturally when they're no longer referenced.
But to do what you appear to want, either your Foo
instance must reference the Bar
instance, or some other object must reference both in order to create the link. It could be a reference to a Bar
instance as a System.Object
, i.e. Foo
doesn't need to know about the Bar
Type.