开发者

Windows Form Closed but not destroyed

In my W开发者_开发百科indows 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?


If it's not destroyed that means the Garbage Collector doesn't think it should be destroyed.

This basically means that you're either:

  1. Holding a reference to the object somewhere
  2. Have the object listening to an event (That's also a kind of reference to the object)

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.


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)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜