C#析构函数超出范围后不调用

use*_*008 2 c# destructor scope

在超出范围之后我遇到了析构函数的问题(它正在调用但是在一段时间之后需要在表单上进行操作,例如更改单选按钮),也许我的代码中存在错误.看一看:

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
            EventLogger.Print += delegate(string output)
            { if (!textBox1.IsDisposed) this.Invoke(new MethodInvoker(() => textBox1.AppendText(output + Environment.NewLine)), null); };
        }

        private void button1_Click(object sender, EventArgs e)
        {
            TestClass test = new TestClass();
        }
    }
    public static class EventLogger
    {
        public delegate void EventHandler(string output);
        public static event EventHandler Print;
        public static void AddLog(String TextEvent)
        {
            Print(TextEvent);
        }
    }
    public class TestClass
    {
        public TestClass()
        {
            EventLogger.AddLog("TestClass()");
        }
        ~TestClass()
        {
            EventLogger.AddLog("~TestClass()");
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

Ed *_* S. 9

对,因为这不是C++.在对象离开其声明范围后,不保证立即调用终结器(不是在C++中的析构函数),当GC决定进入并在您之后清理时调用它.

我可以问你为什么要使用终结器吗?您是否维护对非托管资源的引用,这些资源需要尽可能确定地解除分配(如果是这样,请在IDisposable接口上阅读)?C#终结器的用例很少而且很远,实现它们并不常见.