任何過程中的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」。
編輯:看來我的問題被誤解了,所以我重新編寫了它並提供了一個較小的代碼示例。
這看起來像http://stackoverflow.com/questions/3133199/net-global-exception-handler-in-console-application – Jodrell 2012-07-10 11:03:24
的副本通常應該使用全局異常處理程序進行登錄。如果您對異常情況有所瞭解,您應該在本地處理。 – Jodrell 2012-07-10 11:05:30
這應該工作得很好。當然,你不想使用try/catch,這會阻止UnhandledException事件處理程序的運行。你不必自己照顧Die(),它是自動的。 – 2012-07-10 13:14:05