title: Use AppDomain to load/unload external assemblies
body: <p>My scenario is as follows:</p>
  
  <ul>
  <li>Create new AppDomain</li>
  <li>Load some assemblies into it</li>
  <li>Do some magic with loaded dlls</li>
  <li>Unload AppDomain to release memory &amp; loaded libraries</li>
  </ul>
  
  <p>Below is the code that I'm trying to use</p>
  
  <pre><code>    class Program
  {
      static void Main(string[] args)
      {
          Evidence e = new Evidence(AppDomain.CurrentDomain.Evidence);
          AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
          Console.WriteLine("Creating new AppDomain");
          AppDomain newDomain = AppDomain.CreateDomain("newDomain", e, setup);
          string fullName = Assembly.GetExecutingAssembly().FullName;
          Type loaderType = typeof(AssemblyLoader);
          var loader = (AssemblyLoader)newDomain.CreateInstanceFrom(loaderType.Assembly.Location, loaderType.FullName).Unwrap();
          Console.WriteLine("Loading assembly");
          Assembly asm = loader.LoadAssembly("library.dll");
          Console.WriteLine("Creating instance of Class1");
          object instance = Activator.CreateInstance(asm.GetTypes()[0]);
          Console.WriteLine("Created object is of type {0}", instance.GetType());
          Console.ReadLine();
          Console.WriteLine("Unloading AppDomain");
          instance = null;
          AppDomain.Unload(newDomain);
          Console.WriteLine("New Domain unloaded");
          Console.ReadLine();
      }
  
      public class AssemblyLoader : MarshalByRefObject
      {
          public Assembly LoadAssembly(string path)
          {
              return Assembly.LoadFile(path);
          }
      }
  }
  </code></pre>
  
  <p><em>library.dll</em> consists only of a single dummy class, with one huge string table(for easier tracking the memory consumption)</p>
  
  <p>Now the problem is that memory actually isn't freed. What's more surprising, memory usage actually increases after AppDomain.Unload()</p>
  
  <p>Can anyone shed some light on this issue?</p>