I have a Windows Form Application in which clicking certain buttons create objects from a 2nd Form. On closing this 2nd Form by the user, the memory used by this form is not released (according to Task Manager).
I tried using this.dispose()
on exit button, this.close()
, form2 = null
in the main code, and tried clearing all controls from this form by code before disposing. None of this has worked and every time the user clicks the button, the memory usage by the application increases and memory used by the previous instance is not released.
What shall I use to solve this problem?
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.
Dispose
isn't for releasing memory - the common language runtime's garbage collector takes care of that. Dispose is for releasing other (non-memory) scarce resources like database connections and file handles.
Generally speaking, you don't need to worry about memory consumption in your .NET applications because the framework does it for you. If you need finer control over memory consumption, you should be developing in a language that provides that control, like C++.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With