![](/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.