I want to keep reference of managed ObjB
in ObjA
, and ensure ObjB
instance survives until ObjA
finalized. I need to call some ObjB
methods in ObjA.~ObjA
and only then let ObjB
to die. There is only on reference to ObjB
(in ObjA
obviously). For now I found a way to keep ObjB
alive, I store it in static List<ObjB>
, and remove it from that list on ObjA.~ObjA
.
So the question is - is there some fancy way to exclude object from GC and later enable it from finalizer of another object?
Ultimately, once GC is in play: it is too late - everything is non-deterministic. A will keep B alive, but only if A is also being kept alive. Finalizers shouldn't really talk to any other objects.
There are two solutions to your scenario:
GCHandle
, noting that it is your responsibility to allocate and release the handle appropriatelyThe first option is usually easier and more appropriate.