我在.NET应用程序中卸载AppDomain时遇到问题。
我有以下代码,它只是在目录中加载dll并检查它们是否具有某个属性:
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;
这适用于所有具有相关属性的dll。但我有一个dll,其中包含对第三方dll的引用(PelcoSDK.dll,请参阅:http://pdn.pelco.com/sdk#sthash.ERuOPMO6.dpbs)
每当包含此dll时,以下行只会冻结:
AppDomain.Unload(appDomain);
从这个链接:https://social.msdn.microsoft.com/Forums/en-US/3f0f10ae-7fcb-459d-9112-6556a9b5b456/appdomainunload-deadlock?forum=csharplanguage我看到可以抛出异常,所以我添加了以下内容:
try
{
AppDomain.Unload(appDomain);
appDomain = null;
}
catch (CannotUnloadAppDomainException ex)
{
string message = ex.Message;
}
catch (AppDomainUnloadedException ex)
{
string message = ex.Message;
}
但是永远不会抛出异常。
ALSO 我在以下事件处理程序中添加了以查看是否有任何调试消息指示Unload未成功的原因但没有报告任何内容( EventArgs为空):
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!");
}
任何人都可以指出卸载会像这样挂起的原因吗?或者有关如何调试它的任何建议?