protected override void OnStartup(StartupEventArgs e)
{
Trace.Listeners.Add(new TextWriterTraceListener("ErrorLog.txt"));
Trace.AutoFlush = true;
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
Application.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;
TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
base.OnStartup(e);
}
private void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
// 主线程UI异常
Trace.TraceError($"主线程UI异常" +e.Exception.ToString());
// Prevent default unhandled exception processing
e.Handled = true;
}
private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
// UnhandledException 其他线程上的异常
//AppDomain.CurrentDomain.UnhandledException事件处理程序通常用于记录未处理的异常信息,而不是阻止应用程序关闭。当AppDomain.CurrentDomain.UnhandledException事件被触发时,
//通常意味着应用程序处于不稳定的状态,
//所以.NET Framework的默认行为是关闭应用程序
Trace.TraceError($"其他线程上的异常" + (e.ExceptionObject as Exception).ToString());
}
private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
{
//应用程序使用了Task或者async/await,那么你应该处理这个事件
Trace.TraceError($"应用程序使用了Task或者async/await" + e.Exception.ToString());
// 调用e.SetObserved()来阻止异常终止进程
e.SetObserved();
}