开发者

Where to dispose resources in a System.Windows.Form-derived class?

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 pro开发者_如何转开发duces 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?


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".


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 into Dispose that I missed.


Form and Control provide a "Disposed" event that may be used to dispose any resources they use.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜