我应该如何优雅地处理错误的AppDomains?
问题描述:
这段代码片段设计不好吗?最初,在finally块中只有一个AppDomain.Unload
。这具有令人遗憾的副作用,其他线程可以继续在AppDomain中运行,而UnhandledException
正在运行,其中包括使用用户输入,因此在计算规模上非常慢(平均实际运行时可能大于1分钟),可能会抛出其他异常并且通常导致更多问题。我一直想着做一个'更好'的方法,所以我把它提交给SO。借给我你的想法。我应该如何优雅地处理错误的AppDomains?
注:我刚刚意识到这里也存在同步问题。是的,我知道他们是什么,让我们保持专注。
mainApp = AppDomain.CreateDomain(ChildAppDomain, null, AppDomain.CurrentDomain.SetupInformation);
try
{
mainApp.ExecuteAssembly(Assembly.GetEntryAssembly().Location);
finished = true;
}
catch (Exception ex)
{
AppDomain.Unload(mainApp);
mainApp = null;
UnhandledException(this, new UnhandledExceptionEventArgs(ex, false));
}
finally
{
if (mainApp != null)
{
AppDomain.Unload(mainApp);
mainApp = null;
}
}
// ...
void UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
if (mainApp != null)
{
AppDomain.Unload(mainApp);
mainApp = null;
}
// [snip]
}
答
我会努力不要重复。而且,您可以像最初那样只用清理最终块中的appdomain来完成这项工作。这个想法是,如果发生未处理的异常,请将其置于一个变量中,并在关闭AppDomain后处理它。
Exception unhandledException = null;
try
{
...
}
catch (Exception ex)
{
unhandledException = ex;
}
finally
{
CleanupAppDomain(mainApp);
}
if (unhandledException != null)
UnhandledException(this, new UnhandledExceptionEventArgs(unhandledException, false));