【发布时间】:2016-12-11 20:23:25
【问题描述】:
与 Visual Studio 中的默认 C# 模板一样,我将 Windows Form 定义为静态对象,如下所示:
public static FormMain formMain;
static void Main()
{
formMain = new FormMain();
Application.Run(formMain);
formMain.Dispose();
}
如您所见,我在调用此静态表单之前为它分配了一个内存空间(使用new),并在表单关闭后释放了内存(使用Dispose)。
但是,在这个静态表单中,我定义了几个非静态对象(比如标签),如下所示:
public FormMain()
{
// some code here
Label myLabel1 = new Label();
Label myLabel2 = new Label();
Label myLabel3 = new Label();
// some code here
}
现在,我有两个问题:
我是否也必须
Dispose这些非静态对象,或者是否在调用formMain.Dispose();行后立即释放它们(释放内存)?如果我需要处理这些非静态对象,我应该在程序的哪个阶段使用
Dispose(例如,在FormClosed或FormClosing事件中)?
注意:我尽量不使用 Visual Studio 中的表单设计工具,而是更喜欢逐行编写表单。
【问题讨论】:
-
Application.Run 已经在示例中处理了表单:“Form 类的 Dispose 方法将在 [the Application.Run] 方法的返回之前被调用。”
-
我问的不是表单,而是表单中定义的非静态对象(
myLabel1、myLabel2等)。 -
FormMain应该释放它创建的成员变量。FormMain是否存储在静态变量中并不重要。 -
一个表单将释放它的所有子控件。假设这些标签被添加到表单中,它们的处理就得到了处理。
-
我的意思是调用表单的 Dispose 方法会导致它在其每个子控件上调用 Dispose。此外,由于表单和控件具有终结器,因此在终结期间任何非托管资源都将被清除。
标签: c# memory-management