简体   繁体   English

垃圾收集不起作用 int .net c#

[英]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?那么为什么 gc 不工作呢?

Play around, and you'll notice that your code works as expected in Release , but not necessarily Debug .试一试,您会注意到您的代码在Release中按预期工作,但不一定在Debug中工作。

This is because the variables p and zp are still in scope at the point that you call GC.Collect() .这是因为变量pzp在您调用GC.Collect()时仍在 scope 中。 They still refer to the person instances.它们仍然引用person实例。

In Release, the GC will happily collect objects referenced by variables which are still in scope, so long as they are not used again.在 Release 中,GC 会很高兴地收集仍然在 scope 中的变量引用的对象,只要它们不再被使用。 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.在Debug中,调试器需要让你查看scope中所有变量的内容,所以GC无法收集。

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.即使在调试中,您也会看到您期望的 output Note that the tiered compilation introduced in .NET 6 affects this, and the above test might not work as expected.请注意,.NET 6 中引入的分层编译会影响这一点,上述测试可能无法按预期工作。

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 :如果您引入一个单独的方法,因此pzp的生命周期是明确限定的,那么即使在.NET 6 的 Debug 中,您也应该看到预期的行为:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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