2012-07-10 98 views
6

任何過程中的WinForms我用:等效System.Windows.Forms.Application.ThreadException爲控制檯應用程序或Windows服務或一般

  • System.Windows.Forms.Application.ThreadException
  • 系統。 Windows.Application.UnhandledException

我應該如何使用非Winforms多線程應用程序?

考慮C#.NET 4.0以下的完整代碼:

using System; 
using System.Threading.Tasks; 

namespace ExceptionFun 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); 
      Task.Factory.StartNew(() => 
       { 
        throw new Exception("Oops, someone forgot to add a try/catch block"); 
       }); 
     } 

     static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) 
     { 
      //never executed 
      Console.WriteLine("Logging fatal error"); 
     } 
    } 
} 

我見過噸的計算器上類似的問題,但沒有包含一個滿意的答覆。大多數答案都是類型:「你應該在你的代碼中包含正確的exe文件處理」或者「使用AppDomain.CurrentDomain.UnhandledException」。

編輯:看來我的問題被誤解了,所以我重新編寫了它並提供了一個較小的代碼示例。

+1

這看起來像http://stackoverflow.com/questions/3133199/net-global-exception-handler-in-console-application – Jodrell 2012-07-10 11:03:24

+1

的副本通常應該使用全局異常處理程序進行登錄。如果您對異常情況有所瞭解,您應該在本地處理。 – Jodrell 2012-07-10 11:05:30

+0

這應該工作得很好。當然,你不想使用try/catch,這會阻止UnhandledException事件處理程序的運行。你不必自己照顧Die(),它是自動的。 – 2012-07-10 13:14:05

回答

0

您不需要任何等價物,CurrentDomain.UnhandledException事件在多線程控制檯應用程序中工作得很好。但由於你開始線程的方式,它並沒有解決你的問題。您的問題中的處理程序不會在Windows和控制檯應用程序中執行。但是,如果你像這樣開始你的線程(例如):

new Thread(() => { 
    throw new Exception("Oops, someone forgot to add a try/catch block"); 
}).Start(); 

它會着火。

Task.Factory.StartNew(...)CurrentDomain.UnhandledException問題在SO上的很多帖子中被討論過。查了一些建議,在這裏:

How to handle all unhandled exceptions when using Task Parallel Library?

What is the best way to catch exception in Task?

相關問題