![](/img/trans.png)
[英]How do I gracefully handle this exception in a background thread in a Windows service?
[英]How should I gracefully handle faulty AppDomains?
此代码段设计不佳吗? 最初,在finally块中只有一个AppDomain.Unload
。 这有一个不可避免的副作用,即其他线程可以在运行UnhandledException
时继续在AppDomain中运行,其中包括使用用户输入,因此在计算规模上非常慢(平均实际运行时间可能> 1分钟),可能会引发其他异常并且通常会导致更多问题。 我一直在考虑采用“更好”的方式做到这一点,因此,我将其提交给SO。 把你的想法借给我。
注意:我刚刚意识到这里也存在同步问题。 是的,我知道它们是什么,让我们保持专注。
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]
}
我会争取不重复。 而且你可以通过清理你的finally块中的appdomain来完成这项工作,就像你最初做的那样。 这个想法是,如果发生未处理的异常,将其放在变量中并在关闭appdomain后处理它。
Exception unhandledException = null;
try
{
...
}
catch (Exception ex)
{
unhandledException = ex;
}
finally
{
CleanupAppDomain(mainApp);
}
if (unhandledException != null)
UnhandledException(this, new UnhandledExceptionEventArgs(unhandledException, false));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.