Calling Dispose
will not clean up the memory used by an object. Dispose
is meant to be used to run user defined code that releases resources that are not automatically released - like file handles, network handles, database connections etc.
The likely culprit is probably the second form attaching events to objects that are outside it (perhaps the first form?) and never unattaching them.
If you have any events in the second form, unattach them in your OnClose override - that will make the second form eligible for garbage collection.
Note, .NET garbage collector is quite unpredictable and it might create a few instances of an object before cleaning up all the older instances that were eligible for collection. A way to know for sure (without resorting to memory profilers) is to put a breakpoint in the finalizer:
public class MyForm : Form {
~MyForm() {
//breakpoint here
}
}
If the finalizer gets called then this class is OK, if not, you still have a leak. You can also give GC a "kick" - but only for troubleshooting purposes - do not leave this code in production - by initiating GC:
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
Put the above code somewhere that runs after you close and dispose the second form. You should hit the breakpoint in MyForm
finalizer.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…