I have a problem with unloading an AppDomain in my .NET application.
I have the following code which:
AppDomainSetup info = new AppDomainSetup();
Assembly arAssembly = typeof(AssemblyResolver).Assembly;
info.ApplicationBase = Path.GetDirectoryName(arAssembly.Location);
AppDomain appDomain = AppDomain.CreateDomain("AssemblyResolver", null, info);
//Find all the assemblies with the attribute defined
AssemblyName[] assemblyNames = null;
AssemblyResolver ar = (AssemblyResolver)appDomain.CreateInstanceAndUnwrap(arAssembly.FullName, typeof(AssemblyResolver).FullName) as AssemblyResolver;
assemblyNames = ar.PrivateFindAssembliesWithAttribute(attributeType, path, includeSubdirs);
//Finally unload the AppDomain
AppDomain.Unload(appDomain); <-- HANGS HERE
appDomain = null;
This works fine for all my dlls that have the attribute in question. BUT I have one dll that includes a reference to a 3rd party dll (PelcoSDK.dll, see: http://pdn.pelco.com/sdk#sthash.ERuOPMO6.dpbs )
Whenever this dll is included the following line just freezes:
AppDomain.Unload(appDomain);
From this link: https://social.msdn.microsoft.com/Forums/en-US/3f0f10ae-7fcb-459d-9112-6556a9b5b456/appdomainunload-deadlock?forum=csharplanguage I see that there are exceptions that can be thrown so I added the following:
try
{
AppDomain.Unload(appDomain);
appDomain = null;
}
catch (CaotUnloadAppDomainException ex)
{
string message = ex.Message;
}
catch (AppDomainUnloadedException ex)
{
string message = ex.Message;
}
BUT the exceptions are never thrown.
ALSO I added in the following event handlers to see if there were any debug messages indicating why the Unload was not successful but there was nothing reported (EventArgs were null):
AppDomain appDomain = AppDomain.CreateDomain("AssemblyResolver", null, info);
appDomain.DomainUnload += new EventHandler(defaultAD_DomainUnload);
appDomain.ProcessExit += new EventHandler(defaultAD_ProcessExit);
public static void defaultAD_DomainUnload(object sender, EventArgs e)
{
Console.WriteLine("Unloaded defaultAD!");
}
private static void defaultAD_ProcessExit(object sender, EventArgs e)
{
Console.WriteLine("Unloaded defaultAD!");
}
Can anyone point to why the Unload would hang like this? Or any suggestions as to how to debug it?
