Here's some sample 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);//<-- Exception thrown here
}
}
}
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 AppDomain.Unload notes:
In some cases, calling Unload causes an immediate CannotUnloadAppDomainException, for ample if it is called in a finalizer.
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.)