Reputation: 1572
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?
Upvotes: 12
Views: 29048
Reputation: 856
Don't call Dispose() method, call ->>>>> Dispose(true) instead and you will be surprised a lot. It actually freeing memory, you may observe an effect in the task manager.
Upvotes: 0
Reputation: 76500
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.
Upvotes: 22
Reputation: 48583
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++.
Upvotes: 3
Reputation: 3806
Sounds like the memory is still being used because disposed object have not been reclaimed by the garbage collector. Try using the GC.Collect() static method to force a garbage collection. Watch out for performance issues as this normally halts your program until it has finished.
GC.Collect();
Upvotes: 0