简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM