問題描述
我想知道最好的方法是如果所有其他方法都失敗了".
I'm wondering what the best way is to have a "if all else fails catch it".
我的意思是,您在應用程序中處理盡可能多的異常,但仍然肯定會有錯誤,所以我需要有一些東西捕獲所有未處理的異常,以便我可以收集信息并存儲將它們保存在數據庫中或將它們提交到 Web 服務.
I mean, you're handling as much exceptions as possible in your application, but still there are bound to be bugs, so I need to have something that catches all unhandled exceptions so I can collect information and store them in a database or submit them to a web service.
AppDomain.CurrentDomain.UnhandledException 事件是否捕獲所有內容?即使應用程序是多線程的?
Does the AppDomain.CurrentDomain.UnhandledException event capture everything? Even if the application is multithreaded?
旁注:Windows Vista 公開了允許任何應用程序的本機 API 函數在崩潰后恢復自己……現在想不出名字……但我寧愿不使用它,因為我們的許多用戶仍在使用 Windows XP.
Side note: Windows Vista exposes native API functions that allow any application to recover itself after a crash... can't think of the name now... but I'd rather not use it, as many of our users are still using Windows XP.
推薦答案
我剛剛玩過 AppDomain 的 UnhandledException 行為,(這是注冊未處理異常的最后階段)
I have just played with AppDomain's UnhandledException behavior, (this is the last stage the unhandled exception is registered at)
是的,在處理完事件處理程序后,您的應用程序將被終止,并顯示令人討厭的...程序停止工作對話框".
Yes, after processing the event handlers your application will be terminated and the nasty "... program stopped working dialog" shown.
:)您仍然可以避免這種情況.
:) You still can avoid that.
退房:
class Program
{
void Run()
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Console.WriteLine("Press enter to exit.");
do
{
(new Thread(delegate()
{
throw new ArgumentException("ha-ha");
})).Start();
} while (Console.ReadLine().Trim().ToLowerInvariant() == "x");
Console.WriteLine("last good-bye");
}
int r = 0;
void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Interlocked.Increment(ref r);
Console.WriteLine("handled. {0}", r);
Console.WriteLine("Terminating " + e.IsTerminating.ToString());
Thread.CurrentThread.IsBackground = true;
Thread.CurrentThread.Name = "Dead thread";
while (true)
Thread.Sleep(TimeSpan.FromHours(1));
//Process.GetCurrentProcess().Kill();
}
static void Main(string[] args)
{
Console.WriteLine("...");
(new Program()).Run();
}
}
P.S.請在更高級別處理未處理的 Application.ThreadException (WinForms) 或 DispatcherUnhandledException (WPF).
P.S. Do handle the unhandled for Application.ThreadException (WinForms) or DispatcherUnhandledException (WPF) at the higher level.
這篇關于.NET - 實現“捕獲所有異常處理程序"的最佳方式是什么?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!