本文告诉大家如何在 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 方法,然后应用程序退出。通过这个方法可以在软件退出前做日志记录

Application.UnhandledException Event (Windows.UI.Xaml)

UWP 中的全局异常处理


本文会经常更新,请阅读原文: https://blog.lindexi.com/post/win10-uwp-%E6%8D%95%E8%8E%B7%E5%90%8E%E5%8F%B0%E7%BA%BF%E7%A8%8B%E5%BC%82%E5%B8%B8.html ,以避免陈旧错误知识的误导,同时有更好的阅读体验。

如果你想持续阅读我的最新博客,请点击 RSS 订阅,推荐使用RSS Stalker订阅博客,或者前往 CSDN 关注我的主页

知识共享许可协议 本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。欢迎转载、使用、重新发布,但务必保留文章署名林德熙(包含链接: https://blog.lindexi.com ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请 与我联系

无盈利,不卖课,做纯粹的技术博客

以下是广告时间

推荐关注 Edi.Wang 的公众号

欢迎进入 Eleven 老师组建的 .NET 社区

以上广告全是友情推广,无盈利