I have a WindowsForm with a panel control which I use to display my UserControls. I add controls this way:
private void AddControl(Control control)
{
panel.Controls.Clear();
control.Size = new Size(panel.Width - 1, panel.Height - 1);
control.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles. Top;
panel.Controls.Add(control);
}
..
AddControl(new ucSomeControl());
I just clicked every button that uses AddControl() and saw memory usage increased every time. I left the application running, doing nothing, for one and a half hour and the memory usage was dropped from 140mb to 138mb, just like 2mbs. Do you think this is normal or am I doing something wrong with my control adding method which I should/could improve for less memory usage?
Followup
I've created 4 versions of my application: Debug, Release, with Dispose, with manuel GC call.
With my original code
There's little difference between debug and release versions of my application when it comes to memory usage, like 5mb. The problem with these versions is that the more I click on buttons, even if I click the same button and create the same UserControl again, memory usage equally increases.
With Dispose
I've added Chris Arnold's Dispose code. Memory usage is significantly lower and although creating more and more controls still increases memory usage, now each control uses a lot less memory. This was a worthy addendum.
With manuel GC call
I've added this code after Dispose:
GC.Collect();
GC.WaitForPendingFinalizers();
Bingo! Even less memory usage than Dispose code. The best part is, even if I create new controls over and over again, the memory usage increases are very small, almost trivial.
I really liked using Dispose + GC method but every single article I've red about manuel GC calls are strongly discouraging its usage. Even if I don't have any custom finalizers/destructors I'm undecided about using it or not..