2009-10-19 46 views
3

這段代碼片段設計不好嗎?最初,在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] 
} 

回答

2

我會努力不要重複。而且,您可以像最初那樣只用清理最終塊中的appdomain來完成這項工作。這個想法是,如果發生未處理的異常,請將其置於一個變量中,並在關閉AppDomain後處理它。

Exception unhandledException = null; 
try 
{ 
    ... 
} 
catch (Exception ex) 
{ 
    unhandledException = ex; 
} 
finally 
{ 
    CleanupAppDomain(mainApp); 
} 

if (unhandledException != null) 
    UnhandledException(this, new UnhandledExceptionEventArgs(unhandledException, false));