c# - .NET WinForm GC 问题

标签 c# .net winforms garbage-collection

这段代码干净吗?

private void button1_Click(object sender, EventArgs e)
{
  frmCustomDialog f = new frmCustomDialog();
  if(f.ShowDialog() == DialogResult.OK)
    TextBox1.Text = f.MyCustomProperty;
}

您是否需要关闭或处置表单 f 或其他任何东西?还是自动进行垃圾回收?

谢谢。

最佳答案

是的,你应该处理表格:

private void button1_Click(object sender, EventArgs e)
{
    using (frmCustomDialog f = new frmCustomDialog())
    {
        if(f.ShowDialog() == DialogResult.OK)
        {
            TextBox1.Text = f.MyCustomProperty;
        }
    }
}

ShowDialog() 不会处理表单,因为您可以重复使用它并再次显示它。如果您不需要这样做,您应该自己处理它。

来自 ShowDialog() 的文档:

Unlike modeless forms, the Close method is not called by the .NET Framework when the user clicks the close form button of a dialog box or sets the value of the DialogResult property. Instead the form is hidden and can be shown again without creating a new instance of the dialog box. Because a form displayed as a dialog box is not closed, you must call the Dispose method of the form when the form is no longer needed by your application.

关于c# - .NET WinForm GC 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/645836/

相关文章:

c# - 如何将 ASP.NET MVC 中的 HTML <select> 多个属性的更新值插入到数据库?

.net - 如何注册 .net exe 公开的 com 接口(interface)?

c# - 如何创建悬停的 C# Winforms 控件

c# - 用于数据采集的快速响应式 GridView?

c# - 追加和读取文本文件

c# - System.webServer 具有无效的子元素 'monitoring'

javascript - 如何终止 SignalR 连接?

.net - 何时重写 OnEventMethod 与处理实际事件

.net - .NET 的 MongoDB 乐观并发控制

.net - 在 VB.NET 中检查空的 TextBox 控件