为什么在这个非常简单的场景中我的 .net 析构函数没有被调用?

发布于 2024-07-14 06:45:03 字数 468 浏览 6 评论 0原文

我有以下代码:

 public class A
    {
        ~A()
        {
            Console.WriteLine("destructor");
        }
    }

 public static A Aref;
 static void Main(string[] args)
    {
        Aref = new A();
        int gen = GC.GetGeneration(Aref);
        Aref = null;
        GC.Collect(gen, GCCollectionMode.Forced);
        Console.WriteLine("GC done");

    }

我认为我的 Finalizer 方法将在调用 GC.Collect 时被调用,但事实并非如此。

谁能解释一下为什么?

I've got the following code :

 public class A
    {
        ~A()
        {
            Console.WriteLine("destructor");
        }
    }

 public static A Aref;
 static void Main(string[] args)
    {
        Aref = new A();
        int gen = GC.GetGeneration(Aref);
        Aref = null;
        GC.Collect(gen, GCCollectionMode.Forced);
        Console.WriteLine("GC done");

    }

I thought my Finalizer method would be called upon my call to GC.Collect, which is not the case.

Can anyone explain me why ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

北城半夏 2024-07-21 06:45:03

GC.Collect() 返回之前不会调用终结器。 终结器在单独的线程中运行 - 您可以通过调用 GC.WaitForPendingFinalizers() 来等待它们。

Finalizers aren't called before GC.Collect() returns. The finalizers are run in a separate thread - you can wait for them by calling GC.WaitForPendingFinalizers().

想你的星星会说话 2024-07-21 06:45:03

在您的示例中,在收集期间不会调用终结器,因为它仍然以可终结队列为根。 然而,它被安排为最终确定,这意味着它将在下一次垃圾收集期间被收集。

如果您想确保收集具有终结器的类型实例,您需要执行两次这样的收集。

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

但通常您不应该自己调用 Collect() 方法。

The finalizer is not called during the collection in your example, cause it is still being rooted by the finalizable queue. It is however scheduled for finalization, which means that it will be collected during the next garbage collection.

If you want to make sure instances of types with a finalizer are collected you need to do two collections like this.

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

But generally you should not call the Collect() method yourself.

鹤仙姿 2024-07-21 06:45:03

即使你要求GC收集,也不确定这个特定的对象是否会被销毁(因为它不可能在当时被收集的一代中)

Even if you ask for the GC to collect, it is unsure that this specific object will be destroyed (as it could not be in the generation being collected at that moment)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文