title: Why does AppDomain.Unload() error in finalizer?
body: <p>Here's some sample code:</p>
  
  <pre><code>using System;
  namespace UnloadFromFinalizer
  {
      class Program
      {
          static void Main(string[] args)
          {
              Program p = new Program();
          }
  
          AppDomain domain;
          Program()
          {
              this.domain = AppDomain.CreateDomain("MyDomain");
          }
  
          ~Program()
          {
              AppDomain.Unload(this.domain);//&lt;-- Exception thrown here
          }
      }
  }
  </code></pre>
  
  <p>I have a class that creates an AppDomain in the constructor to be used over the lifetime of the object.  I'd like to properly cleanup the AppDomain, so I thought I would call Unload in the finalizer.  Unfortunately, that causes a CannotUnloadAppDomainException to be thrown.  The MSDN documentation for <a href="http://msdn.microsoft.com/en-us/library/system.appdomain.unload.aspx" rel="nofollow noreferrer">AppDomain.Unload</a> notes:</p>
  
  <blockquote>
    <p>In some cases, calling Unload causes an immediate CannotUnloadAppDomainException, for ample if it is called in a finalizer.</p>
  </blockquote>
  
  <p>Why is this?  Is the member variable "domain" already cleaned up?  Does that cleanup automatically include unloading the AppDomain, or will it still exist in some unreachable way?  Is there something I should be doing, or can I safely just dump the finalizer?  (I don't really care when the GC gets rid of my object so long as it's fully cleaned up in the process.)</p>