Multiple dead objects
suggest changeWhat if two (or several) otherwise dead objects reference one another? This is shown in the example below, supposing that OtherObject is a public property of FinalizableObject:
var obj1 = new FinalizableObject1();
var obj2 = new FinalizableObject2();
obj1.OtherObject = obj2;
obj2.OtherObject = obj1;
obj1 = null; // Program no longer references Finalizable1 instance
obj2 = null; // Program no longer references Finalizable2 instance
// But the two objects still reference each other
GC.Collect();
GC.WaitForPendingFinalizers();
With the base messages, both instances print "Instance initialized" and, after the pending finalizers run, "Instance finalized". The finalizer order is not guaranteed.
The two objects are finalized and freed from the managed heap despite referencing each other, because no live object still refers to either of them. The collector traces from roots; a cycle that nothing live points at is still garbage.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents