在 System.Windows.Form 派生类中的何处处置资源?
我有一个表单,它在其构造函数中创建了一些我需要处理的一次性资源。但是,C# 表单设计器已在 Designer.cs 文件中生成 Dispose() 方法,该方法中似乎没有任何类型的用户挂钩。所以我不知道如何实现典型的 IDisposable 模式。
该表单偶尔会创建但从未显示,因此使用 Close 事件没有帮助。
有问题的对象不是 IComponents
,因此我不能将它们添加到 this.components
。
我可以在哪里放置此清理代码并确保在处理表单时它会运行?
I've got a form that creates a couple of disposable resources in its constructor that I need to dispose of. However, the C# form designer already produces a Dispose() method in the Designer.cs file that doesn't appear to have any type of user hook in it. So I'm at a loss as to how I'm supposed to implement the typical IDisposable
pattern.
This form is occasionally created but never shown, so using the Close event won't help.
The objects in question are not IComponents
, so I can't just add them to this.components
.
Where can I put this clean-up code and be sure it will run when the form is disposed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以将 Dispose() 方法从 Designer.cs 文件移至源代码文件。并更改它以添加对表单类中任何可处置成员的处置调用。这是可以编辑设计器文件的少数情况之一,您只需远离 #region 内标记为“Windows 窗体设计器生成的代码”的代码即可。
You can move the Dispose() method from the Designer.cs file to your source code file. And alter it to add dispose calls for any disposable members in your form class. This is one of the few cases where it is okay to edit the designer file, you only need to stay away from the code that inside the #region marked "Windows Form Designer generated code".
我经常想知道这个问题,尽管我从未真正遇到过这个问题。您可以使用
已处置
< /a> 事件,尽管可能有更好的方法来挂钩我错过的Dispose
。I've often wondered about this though I never actually ran into an issue with it. You can use the
Disposed
event, although there might be a better way to hook intoDispose
that I missed.表单和控件提供“已处置”事件,可用于处置它们使用的任何资源。
Form and Control provide a "Disposed" event that may be used to dispose any resources they use.