C# AppDomain卸载挂起在.Net应用程序中
我在卸载.NET应用程序中的AppDomain时遇到问题 我有以下代码,只需将DLL加载到目录中并检查它们是否具有特定属性:C# AppDomain卸载挂起在.Net应用程序中,c#,.net,appdomain,C#,.net,Appdomain,我在卸载.NET应用程序中的AppDomain时遇到问题 我有以下代码,只需将DLL加载到目录中并检查它们是否具有特定属性: AppDomainSetup info = new AppDomainSetup(); Assembly arAssembly = typeof(AssemblyResolver).Assembly; info.ApplicationBase = Path.GetDirectoryName(arAssembly.Location); AppDomain appDomai
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;
从这个链接:我看到有一些异常可以抛出,所以我添加了以下内容:
try
{
AppDomain.Unload(appDomain);
appDomain = null;
}
catch (CannotUnloadAppDomainException ex)
{
string message = ex.Message;
}
catch (AppDomainUnloadedException ex)
{
string message = ex.Message;
}
但是不会抛出异常
另外我添加了以下事件处理程序,以查看是否有任何调试消息指示卸载未成功的原因,但未报告任何内容(事件参数为null):
有人能指出为什么卸载会这样挂起吗?或者关于如何调试它的任何建议?您确定不会抛出异常,因为catch块中的语句似乎什么都不做吗?卸载无法完成,直到所有在appdomain中执行代码的线程都中止。当线程不处于可警报的等待状态或执行非托管代码时,线程不会中止。后一个子句应该很有说服力:)如果您不能强制该代码完成其工作,那么您唯一的其他选择就是在另一个可以杀死()的进程中运行它。可能的重复表明它最终会抛出CannotUnloadAppDomainException。我等待了很长时间(30分钟)而且它从未抛出CannotUnloadAppDomainException。我在异常中设置断点,它们从未被命中。
try
{
AppDomain.Unload(appDomain);
appDomain = null;
}
catch (CannotUnloadAppDomainException ex)
{
string message = ex.Message;
}
catch (AppDomainUnloadedException ex)
{
string message = ex.Message;
}
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!");
}