石家庄网站设计公司排名,上传文档网站开发,桂林网站建设服务,广州冼村街道办在Application中存在三种异常事件EventHandler
DispatcherUnhandledExceptionAppDomain.CurrentDomain.UnhandledExceptionTaskScheduler.UnobservedTaskException
其中 DispatcherUnhandledException 是在异常由应用程序引发但未进行处理时发生#xff0c;但无法捕获多线程…在Application中存在三种异常事件EventHandler
DispatcherUnhandledExceptionAppDomain.CurrentDomain.UnhandledExceptionTaskScheduler.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 enabled1/ 可以阻止应用程序奔溃,但是这边我使用的是Net6.0所以没成功
public partial class App{protected override Window CreateShell(){return Container.ResolveMainWindow();}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 enabled1/ 可以阻止应用程序奔溃类似 e.Handletrue}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.AddModuleCodingModuleModule();base.ConfigureModuleCatalog(moduleCatalog);}}