为什么我的析构函数永远不会运行? [英] Why does my destructor never run?

查看:124
本文介绍了为什么我的析构函数永远不会运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个析构函数方法

public partial class Form1 : Form
{
    public Form1()
    {
        System.Diagnostics.Trace.WriteLine("Form1.Initialize " + this.GetHashCode().ToString());
        InitializeComponent();
    }
    ~Form1()
    {
        System.Diagnostics.Trace.WriteLine("Form1.Dispose " + this.GetHashCode().ToString());
    }
}

当表单被破坏,我想它来写到输出窗口:

When the form is destroyed, I want it to write to the output window:


(Form1 opened)
Form1.Initialize 41149443
(Form1 closed)
Form1.Dispose 41149443

MSDN建议实施的析构函数3种方式:

MSDN suggests 3 ways in implementing destructor:

IDisposable的
http://msdn.microsoft.com/en-us/library/system.idisposable.aspx

IDisposable http://msdn.microsoft.com/en-us/library/system.idisposable.aspx

的SafeHandle模式
http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.safehandle.aspx

SafeHandle pattern http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.safehandle.aspx

然而,所有的这些方式写Form1.Dispose 41149443到输出窗口。
因此,我不能够告诉表单是否已经被销毁或没有。建议?


我应该放弃对实现这一目标,由于垃圾收集器的不确定性希望吗?


是有另一种方式知道是否Form1中已经收集垃圾?

However, none of these ways write "Form1.Dispose 41149443" to the output Window. Therefore, I am not able to tell whether the form has been destroyed or not. Suggestions ?

Should I give up hope on achieving this due to uncertainty of garbage collector?

Is there another way to know whether Form1 has been garbage collected ?

推荐答案

只有三种方式来实现你实际列出的析构函数之一包括使用析构函数,这是〜析构函数()

Only one of the three ways to implement a destructor that you list actually involves a destructor, and that's ~Destructor().

如果您实施的IDisposable ,并处理你的对象,那么在的Dispose代码运行,但有没有理由认为你的析构函数。

If you implement IDisposable, and dispose of your object, then the code in Dispose will run, but there's no reason to think that your destructor will.

我觉得你追不可能在这里。析构函数的运行,并在垃圾收集器这样的法令。这并不是说你有任何控制的东西。在GC以及其权利范围内,形成运行析构函数只是浪费时间的意见,如果有足够的内存就会形成这种看法。

I think you chasing the impossible here. Destructors run as and when the garbage collector so decrees. It's not something that you have any control over. The GC is well within its rights to form the opinion that running destructors simply wastes time, and if there is plenty of memory it will form that opinion.

如果你需要预测处置,定稿等,然后用的IDisposable

If you need predictable disposal, finalization etc., then use IDisposable.

这篇关于为什么我的析构函数永远不会运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆