我有一个包含 RichTextBox
的子表单,它加载了 RichText 的资源文件。
当单击关闭子窗体的按钮时(使用 Close()
),窗体关闭并返回到父窗体。但是,资源并未被处置。事实上,在我的鼠标按钮几乎用完之后,内存真的升级了。
作为查看资源最终是否会被释放的测试,我在父级上设置了一个表单计时器来加载子表单,并在子级中设置了另一个计时器来调用 Close()
。这次资源在大约 5 或 6 个打开/关闭周期后被释放。
嗯..我想。所以我改变了设置来模拟现实。这次我将子窗体计时器触发事件更改为包含 button1.PerformClick()
,它会触发 button1
按下事件,其中包含 Close()
声明。这次资源没有被释放,在我中止测试之前内存使用量上升到 1 GB!
为什么包含 Close()
的按钮事件与包含 Close()
的计时器事件不同?
好的..这是打开子窗体的父窗体代码:-
private void showSplashScreen()
{
// Instantiating SplashScreen
SplashScreen splash = new SplashScreen();
// Displaying SplashScreen
splash.ShowDialog();
}
这是子表单上用于关闭表单的代码:-
private void button1_Click( object sender, EventArgs e )
{
Close();
}
private void timer1_Tick( object sender, EventArgs e )
{
button1.PerformClick();
// Close();
}
当以这种方式运行时,内存使用量会增加。但是如果 button1.PerformClick()
被注释掉并且 Close()
被取消注释,资源会定期释放
最佳答案
根据Form.Close MSDN Documentation如果您使用 ShowDialog,您需要手动处理您的资源。我会在 FormClosing 中做什么事件。至于为什么当你使用定时器时它会起作用,我不确定。但通常当我使用 ShowDialog
时,我正在检查 DialogResult,然后从父级关闭表单。尽管像您一样使用 Using
处理起来更干净。
SplashScreen splash = new SplashScreen();
DialogResult dr == splash.ShowDialog();
if (dr == System.Windows.Forms.DialogResult.OK)
{
//Do something
}
else
{
//do something else
}
splash.Close();
splash.Dispose();
The two conditions when a form is not disposed on Close is when (1) it is part of a multiple-document interface (MDI) application, and the form is not visible; and (2) you have displayed the form using ShowDialog. In these cases, you will need to call Dispose manually to mark all of the form's controls for garbage collection.
关于c# - 按钮单击导致子窗体未被处置 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12726390/