07.net6的wpf全局异常处理步骤

  1. 注册并定义3个全局异常事件处理函数
protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            //全局错误处理
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;//Thead,处理在非UI线程上未处理的异常,当前域未处理异常
            DispatcherUnhandledException += App_DispatcherUnhandledException;//处理在UI线程上未处理的异常
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;//处理在Task上未处理的异常
        }

        private void TaskScheduler_UnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e)
        {
            // 处理未被观察的异常
            // 可以记录日志或执行其他操作
            MessageBox.Show("TaskScheduler_UnobservedTaskException出现错误:" + Environment.NewLine + e.Exception.ToString());


            // 标记异常已处理,防止应用程序崩溃
            e.SetObserved();
        }

        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            // 处理未经处理的异常
            // 请注意,这里的异常是无法恢复的,应用程序可能会退出
            MessageBox.Show("CurrentDomain_UnhandledException出现错误:" + Environment.NewLine + e.ExceptionObject.ToString());

        }

        private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            // 处理未经处理的异常
            // 请注意,这里的异常是无法恢复的,应用程序可能会退出
            // 显示错误信息
            MessageBox.Show("App_DispatcherUnhandledException出现错误:" + Environment.NewLine + e.Exception.ToString());

            // 终止事件传播,防止应用程序崩溃
            e.Handled = true;
        }      
  1. 触发异常
//触发异常
        public ICommand TriggerExceptionCommand
        {
            get => new DelegateCommand(async() =>
            {
                触发ui异常,引发App_DispatcherUnhandledException
                //int i = 0;
                //int a = 20 / i;

                不用await引发的是TaskScheduler_UnobservedTaskException出现错误
                使用await引发的是引发App_DispatcherUnhandledException出现错误
                //await Task.Run(() =>
                //{
                //    //int i = 0;
                //    //int a = 20 / i;
                //    App.Current.Dispatcher.Invoke(() =>
                //    {
                //        //不用await引发的是TaskScheduler_UnobservedTaskException出现错误
                //        //使用await引发的是引发App_DispatcherUnhandledException出现错误
                //        int i = 0;
                //        int a = 20 / i;
                //    });
                //});
                
                引发的是CurrentDomain_UnhandledException出现错误
                //new Thread(() =>
                //{
                //    //int i = 0;
                //    //int a = 20 / i;
                //    App.Current.Dispatcher.Invoke(() =>
                //    {
                //        //引发的是CurrentDomain_UnhandledException出现错误
                //        int i = 0;
                //        int a = 20 / i;
                //    });
                //}).Start();
            });
       }

在WPF应用程序中实现全局捕获异常可以使用Application.DispatcherUnhandledException事件。此事件会在未处理的异常冒泡到应用程序的顶层时触发。

可以在App.xaml.cs中的OnStartup方法中添加以下代码来订阅该事件并处理全局异常:

protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            //全局错误处理
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;//Thead,处理在非UI线程上未处理的异常,当前域未处理异常
            DispatcherUnhandledException += App_DispatcherUnhandledException;//处理在UI线程上未处理的异常
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;//处理在Task上未处理的异常
        }

        private void TaskScheduler_UnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e)
        {
            // 处理未被观察的异常
            // 可以记录日志或执行其他操作
            MessageBox.Show("TaskScheduler_UnobservedTaskException出现错误:" + Environment.NewLine + e.Exception.ToString());


            // 标记异常已处理,防止应用程序崩溃
            e.SetObserved();
        }

        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            // 处理未经处理的异常
            // 请注意,这里的异常是无法恢复的,应用程序可能会退出
            MessageBox.Show("CurrentDomain_UnhandledException出现错误:" + Environment.NewLine + e.ExceptionObject.ToString());

        }

        private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            // 处理未经处理的异常
            // 请注意,这里的异常是无法恢复的,应用程序可能会退出
            // 显示错误信息
            MessageBox.Show("App_DispatcherUnhandledException出现错误:" + Environment.NewLine + e.Exception.ToString());

            // 终止事件传播,防止应用程序崩溃
            e.Handled = true;
        }      

在上述代码中,CurrentDomain.UnhandledException事件用于处理在非UI线程上未处理的异常,而DispatcherUnhandledException事件用于处理在UI线程上未处理的异常。在事件处理程序中,可以添加自定义的异常处理逻辑,比如记录日志、提示用户等。

需要注意的是,DispatcherUnhandledException事件中的e.Handled属性应设置为true,以表示已经处理了异常,阻止应用程序继续抛出异常并崩溃。而CurrentDomain.UnhandledException事件中无法设置Handled属性,应用程序可能会直接退出。

此外,还可以考虑使用其他工具和框架来增强全局异常处理,如在App.xaml.cs中配置TaskScheduler.UnobservedTaskException来处理Task异常,或使用第三方的异常处理库(如Serilog、NLog等)来记录异常日志和提供更丰富的异常处理功能。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用 `PdfiumViewer` 这个 NuGet 包将 PDF 文件转换为图片,它可以在 WPF 应用程序中使用。下面是一个简单的示例: 1. 首先,在 Visual Studio 中创建一个 WPF 应用程序。 2. 在项目中添加 `PdfiumViewer` NuGet 包。 3. 创建一个 `PdfToImageConverter` 类,该类包含一个 `ConvertPdfToImage` 方法,该方法将 PDF 文件转换为图片。代码如下: ```csharp using (var document = PdfiumViewer.PdfDocument.Load(pdfFilePath)) { var image = document.Render(0, 300, 300, true); image.Save(imageFilePath, System.Drawing.Imaging.ImageFormat.Jpeg); } ``` 在这个代码中,我们使用 `PdfiumViewer` 中的 `PdfDocument` 类加载 PDF 文件,然后将它渲染成一个 `System.Drawing.Image` 对象,最后保存为 JPEG 格式的图片文件。 4. 在 WPF 应用程序中,创建一个 `Image` 控件用于显示转换后的图片。 5. 在 WPF 应用程序中,使用 `OpenFileDialog` 对话框选择要转换的 PDF 文件,并将其路径传递给 `ConvertPdfToImage` 方法。 6. 将转换后的图片显示在 `Image` 控件中。 完整的代码示例如下: ```csharp public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void ConvertButton_Click(object sender, RoutedEventArgs e) { var openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "PDF Files (*.pdf)|*.pdf"; if (openFileDialog.ShowDialog() == true) { var pdfFilePath = openFileDialog.FileName; var imageFilePath = Path.Combine(Path.GetDirectoryName(pdfFilePath), Path.GetFileNameWithoutExtension(pdfFilePath) + ".jpg"); var converter = new PdfToImageConverter(); converter.ConvertPdfToImage(pdfFilePath, imageFilePath); var image = new BitmapImage(new Uri(imageFilePath)); ImageControl.Source = image; } } } public class PdfToImageConverter { public void ConvertPdfToImage(string pdfFilePath, string imageFilePath) { using (var document = PdfiumViewer.PdfDocument.Load(pdfFilePath)) { var image = document.Render(0, 300, 300, true); image.Save(imageFilePath, System.Drawing.Imaging.ImageFormat.Jpeg); } } } ``` 这个示例将 PDF 文件转换为 JPEG 格式的图片,但你也可以将其保存为其他格式。同时,你还需要添加一些错误处理异常处理的代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值