我必须在FolderBrowserDialog 上调用Dispose 方法吗?
.NET Framework 中的 FolderBrowserDialog
组件(和 OpenFileDialog
)实现了 IDisposible
接口,这意味着我们应该调用它的 Dispose
> 方法在我们完成后的某个适当的时间或者发生了一些不好的事情(非托管资源泄漏)。
在 Visual Studio WinForm 设计器中,如果我将 FolderBrowserDialog
组件拖到窗体上,设计器生成的代码似乎根本不处理此问题,没有代码调用 上的 Dispose 方法>文件夹浏览器对话框
。
相反,如果我拖动一个也实现了 IDisposible 接口的 Timer(System.Windows.Forms 命名空间中的 Timer),则生成的代码将是:
this.components = new System.ComponentModel.Container();
this.timer1 = new System.Windows.Forms.Timer(this.components);
通过将计时器与容器 (this.components) 相关联,可以保证在处置容器时正确处置计时器 - 在 Form.Close()
或 Form 时发生。调用 Dispose()
。
那么为什么 FolderBrowserDialog
组件会受到这种特殊待遇呢?
The FolderBrowserDialog
component in .NET Framework (and the OpenFileDialog
) implements the IDisposible
interface, meaning we should call its Dispose
method at some appropriate time after we've done with it or something bad happens (unmanaged resource leaks).
In Visual Studio WinForm designer, if I drag a FolderBrowserDialog
component onto a Form, the code generated by the designer does not seem to take care of this at all, no code calls the Dispose method on the FolderBrowserDialog
.
In contrast, if I drag a Timer
(the one in the System.Windows.Forms
namespace) which also implements IDisposible
interface, the code generated would be:
this.components = new System.ComponentModel.Container();
this.timer1 = new System.Windows.Forms.Timer(this.components);
By associating the timer with the container (this.components), the timer is guaranteed to be properly disposed when the container is disposed- happens when Form.Close()
or Form.Dispose()
is called.
So why FolderBrowserDialog
component receives this special treatment?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好地方!原因可能是
FolderBrowserDialog
不提供采用IContainer
参数的构造函数,而Timer
则提供。至于为什么会这样,只能去问原来的winforms设计者了。也许它并不是真正设计用于设计师以这种方式使用的?他们只是意味着它可以在
using
语句的代码中使用?请记住,
FolderBrowserDialog
及其父项实际上并未从Component
重写Dispose
,因此它实际上并不需要 处理任何东西。Good spot! The reason is probably that the
FolderBrowserDialog
does not provide a constructor that takes anIContainer
argument, whereasTimer
does.As to why this is so, you can only ask the original winforms designers. Maybe it isn't really designed to be used in the designer in this way? They only meant it to be used in code in a
using
statement?Bear in mind that
FolderBrowserDialog
, and its parents, don't actually overrideDispose
fromComponent
, so it doesn't actually need to dispose anything.