Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

this.Dispose() doesn't release memory used by Form after closing it.

Tags:

c#

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?

like image 329
EgyEast Avatar asked May 30 '10 22:05

EgyEast


2 Answers

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.

like image 145
Igor Zevaka Avatar answered Oct 09 '22 00:10

Igor Zevaka


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++.

like image 44
Jeff Sternal Avatar answered Oct 08 '22 23:10

Jeff Sternal