Windows 窗体关闭但未销毁
在我的 Windows 窗体应用程序中,当我关闭窗体(派生自基本窗体)时,其 FormClosing 和 FormClosed 事件会触发,但析构函数永远不会触发。它仍然保持内存被占用。
关于如何在关闭时完全破坏表单的任何想法?
In my Windows Form application when I close a form (which is derived from a base form), its FormClosing and FormClosed Events fire but destructor never fires off. It still keeps the memory occupied.
Any ideas on how to destroy the form completely when it is closed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果它没有被销毁,则意味着垃圾收集器认为它不应该被销毁。
这基本上意味着您可以:
垃圾收集器不会释放表单,直到没有对它的引用。
如果您有想要处置的重要资源,请将其设为
IDisposable
,并使用Dispose 方法。If it's not destroyed that means the Garbage Collector doesn't think it should be destroyed.
This basically means that you're either:
The garbage collector won't free the Form until there are no references to it.
If you have important resources you want to dispose of, make it
IDisposable
, and use the Dispose method.析构函数(或更准确地说,终结器 - .NET 中没有析构函数)不保证在 .NET 中执行 - 对象可能会在运行时的突发奇想中被清理甚至永远不会。你不能依赖你的终结器方法被调用。
如果您需要在表单关闭时执行某些操作,请处理 Closed 事件。
如果您需要释放非托管资源(例如关闭打开的文件),请将此逻辑添加到 Dispose() 方法中。
如果您担心内存使用,请不要担心内存使用。运行时根据自己的逻辑自动管理内存。
参考:垃圾收集 (MSDN)
Destructors (or more correctly, finalizers - there are no destructors in .NET) are not guaranteed to be executed in .NET - objects may be cleaned up at the whim of the runtime or even never. You cannot rely on your finalizer method ever being called.
If you need to do something when your form is closed, handle the Closed event.
If you need to release an unmanaged resource (e.g. close an open file), add this logic to the Dispose() method.
If you are worried about memory use, do not worry about memory use. The runtime manages memory automatically based on its own logic.
Reference: Garbage Collection (MSDN)