バックグラウンド スレッドで例外が発生した場合はキャッチされないことを除いて、グローバルな try/catch メソッドを試すことができます。アプリドメイン ( msdnAppDomain.UnhandledException
)で未処理の例外を通知する場合に使用できます。プログラムの残りの部分が次のように実行される前に、メインでサインアップします。
static void Main(string[] args)
{
AppDomain.UnhandledException += WriteUnhandledExceptionToFile;
// rest of program
}
static void WriteUnhandledExceptionToFile(object sender, UnhandledExceptionEventArgs args)
{
// write to where ever you can get it.
string path = Path.Combine(Environment.CurrentDirectory, "UnhandledException.txt");
File.WriteAllText(path, args.ExceptionObject.ToString()); // will print message and full stack trace.
}
編集
既定では、Windows フォームと WPF は、UI スレッドでスローされたすべての例外をキャッチすることに注意してください。これらのスレッドで例外が通知されるようにするには、Application.ThreadException イベント (フォーム) または Application.DispatcherUnhandledException イベント (wpf) にサブスクライブする必要があります。このコードは、上記の AppDomain イベントのコードと非常によく似ています。