Windows Forms 的 ShowDialog 与 Dispose

2009年8月23日
我这才明白我以前写的 Windows Forms 的 C# 代码有什么问题了。见下:
 
Remarks
 
When a form is closed, all resources created within the object are closed and the form is disposed. You can prevent the closing of a form at run time by handling the Closing event and setting the Cancel property of the CancelEventArgs passed as a parameter to your event handler. If the form you are closing is the startup form of your application, your application ends.
 
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.
 
可见在调用 ShowDialog 方法,等它返回之后,获取它的 DialogResult 或其他属性,最后就应该调用 Dispose 方法把资源释放掉。否则是不对的。
 
此外,Dispose 方法可以被调用多次,而只有一次的效果,因此如果调用了 Close 方法关闭一个窗体(Close 方法已经包含了对 Dispose 方法的调用),也仍然可以继续调用 Dispose 方法。这样就不用担心 ShowDialog 显示出的对话框的事件处理程序调用了 Close 方法了。
 

“Windows Forms 的 ShowDialog 与 Dispose” 只有一条评论

  1. Yan 在

    晕,我也是同一时期发现这个问题的,手机上开发老OutOfMemoryException…闲逛至此,灌水留名,到此一游~

留下您的评论