【发布时间】:2014-04-05 20:26:10
【问题描述】:
关于Component类MSDN here的Dispose()方法说——
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;
}
}
比方说,form2 拥有一些我需要立即释放的非托管资源并且当然,我希望 form2 被正确地进行垃圾收集。那么,在 form2 上调用 Dispose() 之后,我应该如何 release all references to the Component 呢?我需要设置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();
}
}
方法ShowForm2 退出,但form2 对象肯定没有被垃圾回收。它仍在显示。
【问题讨论】:
标签: c# .net winforms garbage-collection