Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is an object subject to garbage collection?

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;
}
like image 567
Lindenk Avatar asked Jan 14 '23 16:01

Lindenk


1 Answers

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.

like image 176
Zdeslav Vojkovic Avatar answered Jan 27 '23 21:01

Zdeslav Vojkovic