title: How can I prevent CompileAssemblyFromSource from leaking memory?
body: <p>I have some C# code which is using CSharpCodeProvider.CompileAssemblyFromSource to create an assembly in memory.  After the assembly has been garbage collected, my application uses more memory than it did before creating the assembly.  My code is in a ASP.NET web app, but I've duplicated this problem in a WinForm.  I'm using System.GC.GetTotalMemory(true) and Red Gate ANTS Memory Profiler to measure the growth (about 600 bytes with the sample code).</p>
  
  <p>From the searching I've done, it sounds like the leak comes from the creation of new types, not really from any objects that I'm holding references to.  Some of the web pages I've found have mentioned something about AppDomain, but I don't understand.  Can someone explain what's going on here and how to fix it?</p>
  
  <p>Here's some sample code for leaking:</p>
  
  <pre><code>private void leak()
  {
      CSharpCodeProvider codeProvider = new CSharpCodeProvider();
      CompilerParameters parameters = new CompilerParameters();
      parameters.GenerateInMemory = true;
      parameters.GenerateExecutable = false;
  
      parameters.ReferencedAssemblies.Add("system.dll");
  
      string sourceCode = "using System;\r\n";
      sourceCode += "public class HelloWord {\r\n";
      sourceCode += "  public HelloWord() {\r\n";
      sourceCode += "    Console.WriteLine(\"hello world\");\r\n";
      sourceCode += "  }\r\n";
      sourceCode += "}\r\n";
  
      CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, sourceCode);
      Assembly assembly = null;
      if (!results.Errors.HasErrors)
      {
          assembly = results.CompiledAssembly;
      }
  }
  </code></pre>
  
  <p><strong>Update 1:</strong> This question may be related: <a href="https://stackoverflow.com/questions/1162686/dynamically-loading-and-unloading-a-a-dll-generated-using-csharpcodeprovider">Dynamically loading and unloading a a dll generated using CSharpCodeProvider </a></p>
  
  <p><strong>Update 2:</strong> Trying to understand application domains more, I found this: <a href="http://codebetter.com/blogs/raymond.lewallen/archive/2005/04/03/61190.aspx" rel="nofollow noreferrer">What is an application domain - an explanation for .Net beginners</a></p>
  
  <p><strong>Update 3:</strong> To clarify, I'm looking for a solution that provides the same functionality as the code above (compiling and providing access to generated code) without leaking memory.  It looks like the solution will involve creating a new AppDomain and marshaling.</p>