title: c# thread memory usage
body: <p>I was learning more about threading, and i created a rather simple WPF application with the following code (x64 platform build)</p>
  
  <pre><code>public partial class MainWindow : Window
  {
      public MainWindow()
      {
          InitializeComponent();
  
          for (var i = 0; i &lt;= 20000; i++)
          {
              Thread thread = new Thread(Test);
              thread.IsBackground = true;
  
              thread.Start();
          }
      }
  
      public void Test()
      {
          Thread.Sleep(20000);
      }
  }
  </code></pre>
  
  <p>When i run this code, process takes approximately 560MB of RAM while all threads are running / sleeping.</p>
  
  <p><a href="https://i.stack.imgur.com/hGtXb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hGtXb.png" alt="Highest peak"></a></p>
  
  <p>Upon it's completion, process usage is down to aprox 125 MB of RAM.</p>
  
  <p>My question is, why does process use 125 MB of RAM at that point, when application itself (without thread example) is using only 30 MB of RAM?</p>
  
  <p>Does it keep some of the threads alive for possible re/usage or something else is going on?</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p><em>Due to some suggestions how to improve this code, I would like to point out that I am not asking a way to improve it, but to pinpoint the reason for this behavior.</em></p>
  
  <p><strong>EDIT 2:</strong></p>
  
  <p>This is not a thread related, but I have tried a case with a large <code>string</code> list in memory, and it did not produce same results. When list was fully loaded in memory, it took about 1.3 GB of memory, but after list was set to <code>NULL</code>, and <code>GC.Collect()</code> was called, memory usage dropped back to 30 MB as expected.</p>
  
  <p>Code:</p>
  
  <pre><code>public partial class MainWindow : Window
  {
      List&lt;string&gt; stringArray = new List&lt;string&gt;();
  
      public MainWindow()
      {
          InitializeComponent();
  
  
          for (var i = 0; i &lt;= 100000000; i++)
          {
              //Thread thread = new Thread(Test);
              //thread.IsBackground = false;
  
              //thread.Start();
  
              stringArray.Add("Some very long string to pump up the memory volume 2 reloaded");
          }
  
          stringArray = null;
          GC.Collect();
      }
  
  
  
  }
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/Mkvcw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Mkvcw.png" alt="Lowest peak"></a></p>