WPF全局异常处理,防止程序意外崩溃

public partial class App : Application
    {
        App()
        {              
            this.Startup += App_Startup;
        }

        private void App_Startup(object sender, StartupEventArgs e)
        { 
            this.DispatcherUnhandledException += App_DispatcherUnhandledException;                     
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;        
        }

        //主线程未处理异常
        private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            DoSomething(e.Exception);
            e.Handled = true;
        }

        //未处理线程异常(如果主线程未处理异常已经处理,该异常不会触发)
        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            if (e.ExceptionObject is Exception ex)
            {
                DoSomething(ex);
            }
        }

        //未处理的Task内异常
        private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
        {
            DoSomething(e.Exception);
        }

        //保存、显示异常信息
        private void ProcessException(Exception exception)
        { 
            //保存日志
            //提醒用户
        }
    }

你可能感兴趣的:(wpf,visualstudio)