ati*_*yar 2 .net c# garbage-collection winforms
关于MSDN 类的Dispose()方法,这里说 - Component
The Dispose method leaves the Component in an unusable state. After calling Dispose, you must release all references to the Component so the garbage collector can reclaim the memory that the Component was occupying.
现在让我们说,我有以下代码 -
public partial class Form1 : Form
{
private Form2 form2;
public Form1()
{
InitializeComponent();
form2 = new Form2();
}
private void button1_Click(object sender, EventArgs e)
{
form2.Show();
//do something with form2
form2.Dispose();
??? ??? ???
//form2 = null;
}
}
Run Code Online (Sandbox Code Playgroud)
让我们说,窗口2持有一些非托管资源,我需要被立即释放和当然的,我想窗口2被正确地收集垃圾。那么,release all references to the Component在调用Dispose()form2之后我到底应该怎么做?我需要设置form2 = null;什么的吗?请指教。先谢谢了。
编辑 :
你提到——
even if it were scoped to the method it would be free for garbage collection as soon as the method exits
你能说出form2在以下情况下对象究竟发生了什么吗?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
this.ShowForm2();
}
private void ShowForm2()
{
Form2 form2 = new Form2();
form2.Show();
}
}
Run Code Online (Sandbox Code Playgroud)
该方法ShowForm2退出,但该form2对象绝对没有被垃圾收集。它仍然显示。
嗯,是的,设置唯一的null作品引用,但你的例子是人为的。在编写良好的代码中,您只需Form2为函数创建一个本地实例:
private void button1_Click(object sender, EventArgs e)
{
using (var form2 = new Form2())
{
// do something with form2
}
}
Run Code Online (Sandbox Code Playgroud)
现在您无需担心任何事情,因为您尽可能缩小了对象的范围。
您不希望对Disposed 对象进行实时引用,因为在处理它们之后,您可以使用它们。我编写了相当多的 C# 并且从未为此目的将变量显式设置为 null。您可以以更具确定性的方式管理对象生命周期。
编辑:
根据您的编辑和问题:
方法 ShowForm2 退出,但 form2 对象绝对没有被垃圾收集。它仍然显示。
是的,在这种情况下,表单在关闭之前不能被 GC 处理(并且您也没有调用Dispose()它。)那是因为表单的 GC“根”仍然存在,尽管它在您的代码。
正确的说法是,当一个对象不再被应用程序使用时,它就有资格进行 GC。可以在这里找到更深入的了解。