Search code examples
c#garbage-collection

How to keep managed object alive until finalizer is called?


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?


Solution

  • 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:

    1. Make sure that A stays reachable via some object root, so neither A nor B becomes collectable, or
    2. Use a GCHandle, noting that it is your responsibility to allocate and release the handle appropriately

    The first option is usually easier and more appropriate.