When is an object subject to garbage collection?

2019-01-26 17:20发布

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;
}

1条回答
老娘就宠你
2楼-- · 2019-01-26 17:33

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.

查看更多
登录 后发表回答