title: Adding and removing controls and memory usage in WindowsForm
body: <p>I have a WindowsForm with a panel control which I use to display my UserControls. I add controls this way:</p>
  
  <pre><code>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());
  </code></pre>
  
  <p>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?</p>
  
  <h2>Followup</h2>
  
  <p>I've created 4 versions of my application: Debug, Release, with Dispose, with manuel GC call.</p>
  
  <p><strong>With my original code</strong></p>
  
  <p>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.</p>
  
  <p><strong>With Dispose</strong></p>
  
  <p>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.</p>
  
  <p><strong>With manuel GC call</strong></p>
  
  <p>I've added this code after Dispose:</p>
  
  <pre><code>GC.Collect();
  GC.WaitForPendingFinalizers();
  </code></pre>
  
  <p>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.</p>
  
  <p>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..</p>