private void RegisterEvents()
{
//Task线程内未捕获异常处理事件
TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;//Task异常
//UI线程未捕获异常处理事件(UI主线程)
DispatcherUnhandledException += App_DispatcherUnhandledException;
//非UI线程未捕获异常处理事件(例如自己创建的一个子线程)
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
}
//Task线程内未捕获异常处理事件
private void TaskScheduler_UnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e)
{
try
{
Exception? exception = e.Exception as Exception;
if (exception != null)
{
this.Logger.Error(exception);
}
}
catch (Exception ex)
{
this.Logger.Error(ex);
}
finally
{
e.SetObserved();
}
}
//非UI线程未捕获异常处理事件(例如自己创建的一个子线程)
private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
try
{
var exception = e.ExceptionObject as Exception;
if (exception != null)
{
this.Logger.Error(exception);
}
}
catch (Exception ex)
{
this.Logger.Error(ex);
}
finally
{
//ignore
}
}
//UI线程未捕获异常处理事件(UI主线程)
private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
try
{
this.Logger.Error(e.Exception);
}
catch (Exception ex)
{
this.Logger.Error(ex);
}
finally
{
e.Handled = true;
}
}