title: How is my Session variable usage causing a memory leak?
body: <p>While managing a piece of code, it's become increasingly clear that it's causing the Application Pool it's hosted in to increasingly consume memory. We're able to get around this issue in IIS by setting an automatic reset interval to bring the memory consumption back down or by setting a memory cap for the process, after which it resets, but in either case, we get an unwanted loss of Session variables and an interruption of whatever processes happen to be running at the time.</p>
  
  <p>On a hunch, we wrote a test application to test out a theory that Session variables might be behind this memory consumption, and found that even in a simple application with a single (large) Session variable, we were able to duplicate the issue. Below is the code we put in the Page_Load event:</p>
  
  <pre><code>DataTable table = new DataTable();
  table.Columns.Add("GUID", typeof(string));
  table.Columns.Add("Value", typeof(int));            
  for (int i = 0; i &lt; 1000; i++)
  {
      table.Rows.Add(System.Guid.NewGuid(), i);    
  }            
  Session["Table"] = table;
  </code></pre>
  
  <p>With every reload, the amount of memory consumed increases. Regardless of how long we wait, the memory consumption doesn't go back down, so the Session variables don't seem to be properly garbage collected.</p>
  
  <p>We tried starting the load by clearing out the Session variable with:</p>
  
  <pre><code>Session["Table"] = null
  </code></pre>
  
  <p>or</p>
  
  <pre><code>DataTable tableFree = Session["Table"] as DataTable;
  tableFree = null;
  Session["Table"] = null;
  </code></pre>
  
  <p>and found that in both cases, these changes didn't seem to make a difference (possibly because the Session it had been saved to had already ended?). Does anyone know of any problems storing objects in session variables or with the subsequent garbage collection?</p>