在Application中存在三种异常事件EventHandler
- DispatcherUnhandledException
- AppDomain.CurrentDomain.UnhandledException
- TaskScheduler.UnobservedTaskException
其中 DispatcherUnhandledException
是在异常由应用程序引发但未进行处理时发生,但无法捕获多线程异常
AppDomain.CurrentDomain.UnhandledException
专门捕获所有线程中的异常(不包括Task)
TaskScheduler.UnobservedTaskException
捕获Task中的异常
这些异常Handler可以在应用程序出现异常是记录日志,或者挽回应用程序奔溃的问题。
举例说明
以下异常会触发 DispatcherUnhandledException
以及 AppDomain.CurrentDomain.UnhandledException
执行顺序是 DispatcherUnhandledException
=> AppDomain.CurrentDomain.UnhandledException
int x = 0;
_ = 1 / x;
以下异常会触发 AppDomain.CurrentDomain.UnhandledException
new Thread(() => { _ = 1 / x; }).Start();
以下异常会触发 TaskScheduler.UnobservedTaskException
Task中的异常并不是立刻就能捕获到的,而是等到垃圾回收的时候进行捕获。如果想立刻进行捕获则可以调用GC.Collect(0);和GC.WaitForPendingFinalizers();
Task.Run(() => { _ = 1 / x; });
以下是在Prism框架下的异常处理,其中 Task异常不会导致应用程序奔溃,
DispatcherUnhandledException
异常可以通过e.Handled = true;
表明该异常已被处理,不会造成程序崩溃和退出。
AppDomain.CurrentDomain.UnhandledException
在.Net FrameWork中可以通过设置在 App.config <runtime>
节点下添加 <legacyUnhandledExceptionPolicy enabled="1"/>
可以阻止应用程序奔溃,但是这边我使用的是Net6.0所以没成功!
public partial class App{protected override Window CreateShell(){return Container.Resolve<MainWindow>();}protected override void OnInitialized(){#region 全局异常事件配置// 在异常由应用程序引发但未进行处理时发生,但无法捕获多线程异常// UI线程中的异常 UnhandledException 和 DispatcherUnhandledException 都会捕获 执行顺序是 DispatcherUnhandledException => UnhandledExceptionthis.DispatcherUnhandledException += App_DispatcherUnhandledException;// 专门捕获所有线程中的异常 AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;// 专门捕获Task异常TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;#endregion// 初始化menu 并导航到一个页面IStartService startService = App.Current.MainWindow.DataContext as IStartService;startService.Start();base.OnInitialized();}private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e){Console.WriteLine("---捕获Task异常---");e.SetObserved();}private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e){Console.WriteLine("---所有线程中的异常---");MessageBox.Show((e.ExceptionObject as Exception).Message);//在.Net6.0中无效 --- 在 app.config <runtime> 节点下添加 <legacyUnhandledExceptionPolicy enabled="1"/> 可以阻止应用程序奔溃类似 e.Handle=true}private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e){MessageBox.Show("应用程序异常:" + e.Exception.Message);// 表明该异常已被处理,不会造成程序崩溃和退出e.Handled = true;}protected override void RegisterTypes(IContainerRegistry containerRegistry){}protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog){// 添加Coding模块moduleCatalog.AddModule<CodingModuleModule>();base.ConfigureModuleCatalog(moduleCatalog);}}