title: Garbage collecting in a ThreadPool?
body: <p>I need to handle http requests and the best way I found was using a ThreadPool. Please dont recommend using a finished library, because when I try to do something similar, there will be the same problem(s)!</p>
  
  <p>When try a DDOS-Tool on my own webserver the cpu usage gets high and the memory increases incredible fast!</p>
  
  <p>When I stop the tool the memory usage still increases (see screenshot)!</p>
  
  <p>I want the program to decrease its memory usage after the DDOS-Tool has been stopped.</p>
  
  <p>But unfortunately it does not!</p>
  
  <p>Here is my code: You can try it. It does not need any libraries!</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.IO;
  using System.Net.Sockets;
  using System.Threading;
  
  namespace Webserver
  {
    class Program
    {
      static void Main(string[] args)
      {
        TcpListener tcpListener = new TcpListener(81);
        tcpListener.Start();
        while (true)
          ThreadPool.QueueUserWorkItem(DoWork, tcpListener.AcceptTcpClient());
      }
  
      static void DoWork(object arg)
      {
        try
        {
          using (TcpClient tcpClient = (TcpClient)arg)
          {
            tcpClient.ReceiveTimeout = 500;
            tcpClient.SendTimeout = 500;
  
            using (NetworkStream networkStream = tcpClient.GetStream())
            {
              networkStream.ReadTimeout = 500;
              networkStream.WriteTimeout = 500;
  
              List&lt;string&gt; headers = new List&lt;string&gt;();
  
              using (StreamReader streamReader = new StreamReader(networkStream))
              using (StreamWriter streamWriter = new StreamWriter(networkStream))
              {
                while (true)
                {
                  string line = streamReader.ReadLine();
  
                  if (line == "") break;
                  else headers.Add(line);
                }
  
                Console.WriteLine(headers[0]);
  
                streamWriter.WriteLine("HTTP/1.0 200 OK");
                streamWriter.WriteLine("Server: Webserver");
                streamWriter.WriteLine("Content-Type: text/html; charset=UTF-8");
                streamWriter.WriteLine("");
                streamWriter.WriteLine("Hello World!");
              }
            }
          }
        }
        catch (Exception ex)
        {
          Console.ForegroundColor = ConsoleColor.Red;
          Console.WriteLine(ex.Message);
          Console.ResetColor();
        }
      }
    }
  }
  </code></pre>
  
  <p><img src="https://i.stack.imgur.com/WqaPj.png" alt="Screenshot of Process Hacker&#39;s statistcs"></p>
  
  <p>The red lines mark the timestamps when I started and stopped the ddos-Tool. As you can see, the memory still increases after the tool has been stopped.</p>
  
  <p>I want my program to get down back to 17 MB memory usage as it was at the beginning.</p>