ILovePizza
ILovePizza

Reputation: 191

garbage collection not working int .net c#

I am working with this code as an example:

var p = new person("Amir");
var zp = new person("Amiraa");
GC.Collect();
GC.WaitForPendingFinalizers();

class person
{
    public person(string nName)
    {
        Console.WriteLine("New");
        string name = nName;
    }

    ~person()
    {
        Console.WriteLine("Garbage collected");
    }
}

But the resault on the console only shows "New", not "Garbage collected". so why is the gc not working?

Upvotes: 3

Views: 947

Answers (1)

canton7
canton7

Reputation: 42225

Play around, and you'll notice that your code works as expected in Release, but not necessarily Debug.

This is because the variables p and zp are still in scope at the point that you call GC.Collect(). They still refer to the person instances.

In Release, the GC will happily collect objects referenced by variables which are still in scope, so long as they are not used again. In Debug, the debugger needs to let you view the contents of all variables which are in scope, so the GC can't collect them.

If you do:

var p = new person("Amir");
var zp = new person("Amiraa");

p = null;
zp = null;

GC.Collect();
GC.WaitForPendingFinalizers();

You'll see the output you expect, even in Debug. Note that the tiered compilation introduced in .NET 6 affects this, and the above test might not work as expected.

If you introduce a separate method, so the lifetimes of p and zp are explicitly scoped, you should see the expected behaviour even on .NET 6 in Debug:

Test();
GC.Collect();
GC.WaitForPendingFinalizers();

void Test()
{
    var p = new person("Amir");
    var zp = new person("Amiraa");
}

Upvotes: 7

Related Questions