In c#, an object is subject to garbage collection when there are no references to it. Assuming that is the case, would either of the following ever be collected or is the garbage collector smart enough to discard them both?
class Program
{
static void Main()
{
A a = new A();
a.b = new B();
a.b.a = a;
a = null;
}
{
class A
{
public B b;
}
class B
{
public A a;
}
They will both become eligible for collection as soon as they are not needed anymore. This means that under some circumstances, objects can be collected even before the end of the scope in which they were defined. On the other hand, the actual collection might also happen much later.
.NET garbage collector is not based on reference counting, so cyclic dependency makes no difference.
It is based on mark-and-sweep algorithm, which treats all objects as candidates for collection and then traverses the object graph from the available roots (local variables, static variables), marking them as still 'alive'. Those that don't get marked as still being in use, get collected. Please note that this is a bit simplified description: the real algorithm in .NET is adapted mark-and-sweep, managed heap is divided into 3 generations + large object heap, finalization is completely ignored, etc.
I suggest checking Maoni Stephens' blog for more information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With