为什么在这个非常简单的场景中我的 .net 析构函数没有被调用?
我有以下代码:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在
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 callingGC.WaitForPendingFinalizers()
.在您的示例中,在收集期间不会调用终结器,因为它仍然以可终结队列为根。 然而,它被安排为最终确定,这意味着它将在下一次垃圾收集期间被收集。
如果您想确保收集具有终结器的类型实例,您需要执行两次这样的收集。
但通常您不应该自己调用
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.
But generally you should not call the
Collect()
method yourself.即使你要求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)