本文告诉大家如何在 UWP 中捕获全局的后台线程异常,在出现后台线程异常时,将会让 UWP 程序闪退,但是在退出之前还是可以执行自己的代码
在 UWP 中,如果需要捕获前台线程,也就是 UI 线程的异常,可以参见 UWP 中的全局异常处理 的方法
在 App 的构造函数添加 UnhandledException 事件,在事件方法里面通过参数 UnhandledExceptionEventArgs 可以设置当前这个异常是否被处理,如设置为 true 那么就是被处理的异常,此时的应用不会闪退
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
UnhandledException += App_UnhandledException;
}
private void App_UnhandledException(object sender, Windows.UI.Xaml.UnhandledExceptionEventArgs e)
{
e.Handled = true;// 设置为 true 那么表示这个异常被处理,应用不会闪退
}
如果是后台线程异常,需要使用 AppDomain.CurrentDomain.UnhandledException 事件
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
}
private void CurrentDomain_UnhandledException(object sender, System.UnhandledExceptionEventArgs e)
{
// 后台线程异常,执行到这里的应用就会闪退
}
触发后台线程异常很简单,请看下面代码
var thread = new Thread(() => throw new Exception());
thread.Start();
执行到创建线程然后在线程抛出异常,将会进入 CurrentDomain_UnhandledException
方法,然后应用程序退出。通过这个方法可以在软件退出前做日志记录