Form Memory Management

  • Thread starter Thread starter Steven Blair
  • Start date Start date
S

Steven Blair

Hi,

A GUI I have been writing appears to be using a lot of memory. The amount of
memory being used (Windows Task Manager) rarely decreases.

When I open a new form, most of the time the memory usage increases. I was
under the impression C#'s Garbage collector handled this for the
programming?


Here is one of two examples of things I am doing:


if(MDIChildCheck(typeof(frmDBConfig)) )

{

frmDBConfig f = new frmDBConfig();

f.MdiParent = this;

f.Show();

}


Once this form is closed, would the memory be released? (The form is closed
this.Close();)


Another example:


Form f=this.ActiveMdiChild;


if(this.ActiveMdiChild.GetType() == typeof(frmUsers))

{

((frmUsers)f).EditUser();

}


Again, I am assuming the memory would be released?


The problem I see is, my application memory usage just keeps on growing, and
eventually would eat up the PC's resources. I think I understand that when
the application is completely stopped, the GC would release the memory.


Any help on this matter would be appreciated.


Regards,


Steven
 
It is likely that what you are seeing is perfectly normal. When a form
loads, you will see a (rather largish) amount of memory reserved. You are
expecting the garbage collector to clean some of of this up, and it will --
but probably not immediately. The act of garbage collection is a
performance hit, so the GC doesn't start getting really aggressive
(generation 1 or 2) until the system is beginning to run low on memory. You
just have to trust it.

Now there are a few things that you can do to help out.

Be mindful of objects that support IDisposable, and call Dispose (sometimes
Close) on those objects (or use them within a using{} statement).

If you write a class that uses some kind of resource (files, or whatever),
Make sure to support IDisposeable, and call Dispose on them when you are
finished with them.

Avoid Finalizers. If at all possible, don't use the destructor syntax in
C#. This automatically causes the object (and therefore all objects that it
references) to stay around in memory for at least one extra collection. If
you do have to use a finalizer (usually only if you are wrappering a
unmanaged resource that stays persistant with the object, like a windows
handle to something) make extra sure to support IDispose correctly. You can
read pattern information here:
http://msdn.microsoft.com/library/d.../en-us/cpgenref/html/cpconfinalizedispose.asp

For more general information on the "large form at startup issue", just
search this newsgroup. It's a common question, and you will find tons of
posts on it.
 
Back
Top