全局异常捕获

发布时间 2023-12-04 14:36:16作者: ZHIZRL

DispatcherUnhandledException——UI线程未被处理的异常捕获

从App对象中订阅DispatcherUnhandledException事件

    public partial class App : Application
    {
        public App()
        {
            // Dispatcher   UI线程    未被处理的异常
            this.DispatcherUnhandledException += App_DispatcherUnhandledException;
        }
        private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            MessageBox.Show(e.Exception.Message);
        }
    }

 在按钮事件下触发未使用try-catch捕获的异常,会触发DispatcherUnhandledException事件

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //try
            //{
            int i = 0;
            var result = 100 / i;
            //}
            //catch (Exception ex)
            //{

            //}
        }

 AppDomain.CurrentDomain.UnhandledException——非UI线程未被处理的异常捕获

从AppDomain.CurrentDomain对象中订阅UnhandledException事件

    public partial class App : Application
    {
        public App()
        {
            // Dispatcher   UI线程    未被处理的异常
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
        }
        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            // 记录下日志
        }
    }

 在按钮事件下触发Thread线程报错,异常会触发UnhandledException事件

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var thread = new Thread(new ThreadStart(() =>
            {
                int i = 0;
                var result = 100 / i;
            }));
            thread.Start();
            //thread.IsBackground = true;
        }

 TaskScheduler.UnobservedTaskException——未被观察到的Task异常捕获

 从TaskScheduler对象中订阅UnobservedTaskException事件

public partial class App : Application
    {
        public App()
        {
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
        }
        private void TaskScheduler_UnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e)
        {
            
        }
    }

创建两个按钮事件

在按钮1事件下执行Task线程报错,异常会在Task块被GC回收时触发UnobservedTaskException事件

在按钮2事件下执行一次GC回收

private void Button_Click(object sender, RoutedEventArgs e)
        {
           var t= Task.Run(() =>
            {
                int i = 0;
                var result = 100 / i;
            });
        }
        private void Button_Click1(object sender, RoutedEventArgs e)
        {
            GC.Collect();
        }