【发布时间】:2015-05-17 03:31:05
【问题描述】:
我有一个带有位图的用户控件,当表单关闭时应该处理这些位图。在表单的 Closing 事件、Closed 事件或其他地方执行此操作是否更好?
第 2 部分: 在用户控件内部,当其窗体关闭时,位图应该在 Disposed 事件中还是在其他地方释放?
【问题讨论】:
-
Closing事件。Closed事件为时已晚。
我有一个带有位图的用户控件,当表单关闭时应该处理这些位图。在表单的 Closing 事件、Closed 事件或其他地方执行此操作是否更好?
第 2 部分: 在用户控件内部,当其窗体关闭时,位图应该在 Disposed 事件中还是在其他地方释放?
【问题讨论】:
Closing 事件。 Closed 事件为时已晚。
不,表单与用户控件的私有成员无关。通用 .NET 规则也适用于此,类需要在其自己的 Dispose() 方法中释放其成员。它会在表单关闭时自动运行,无需任何帮助。
然而,有一个怪癖,UserControl 的项目项模板很尴尬。它将 Dispose() 方法放在控件的 Designer.cs 文件中。最好的办法是将此方法剪切+粘贴到控件的主源文件中。编辑方法后,它应该类似于:
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) {
someBitmap.Dispose(); // <== added
someOtherBitmap.Dispose();
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
一些程序员真的不喜欢修改 Designer.cs 文件,请注意没有什么可担心的,因为代码位于标记为 Component Designer generated code 的#region 之外。另一种方法是使用 Disposed 事件:
public UserControl1() {
InitializeComponent();
this.Disposed += UserControl1_Disposed;
}
void UserControl1_Disposed(object sender, EventArgs e) {
someBitmap.Dispose();
someOtherBitmap.Dispose();
}
【讨论】: