Следует использовать как AppDomain.UnhandledException, так и Application.DispatcherUnhandledException?
После прочтения нескольких отличных постов о разнице между AppDomain.UnhandledException и Application.DispatcherUnhandledException кажется, что я должен обработать оба. Это связано с тем, что с гораздо большей вероятностью пользователь может восстановиться после исключения, выдаваемого основным потоком пользовательского интерфейса (т. Е. Application.DispatcherUnhandledException). Правильный?
Кроме того, я должен также дать пользователю возможность продолжить программу для обоих или только Application.DispatcherUnhandledException?
Пример кода ниже обрабатывает как AppDomain.UnhandledException, так и Application.DispatcherUnhandledException, и оба дают пользователю возможность попытаться продолжить, несмотря на исключение.
[спасибо, и часть кода ниже взята из других ответов]
App.xaml
<code><Application x:Class="MyProgram.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Startup="App_StartupUriEventHandler" Exit="App_ExitEventHandler" DispatcherUnhandledException="AppUI_DispatcherUnhandledException"> <Application.Resources> </Application.Resources> </Application> </code>
App.xaml.cs [отредактировано]
<code>/// <summary> /// Add dispatcher for Appdomain.UnhandledException /// </summary> public App() : base() { this.Dispatcher.UnhandledException += OnDispatcherUnhandledException; } /// <summary> /// Catch unhandled exceptions thrown on the main UI thread and allow /// option for user to continue program. /// The OnDispatcherUnhandledException method below for AppDomain.UnhandledException will handle all other exceptions thrown by any thread. /// </summary> void AppUI_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e) { if (e.Exception == null) { Application.Current.Shutdown(); return; } string errorMessage = string.Format("An application error occurred. If this error occurs again there seems to be a serious bug in the application, and you better close it.\n\nError:{0}\n\nDo you want to continue?\n(if you click Yes you will continue with your work, if you click No the application will close)", e.Exception.Message); //insert code to log exception here if (MessageBox.Show(errorMessage, "Application User Interface Error", MessageBoxButton.YesNoCancel, MessageBoxImage.Error) == MessageBoxResult.No) { if (MessageBox.Show("WARNING: The application will close. Any changes will not be saved!\nDo you really want to close it?", "Close the application!", MessageBoxButton.YesNoCancel, MessageBoxImage.Warning) == MessageBoxResult.Yes) { Application.Current.Shutdown(); } } e.Handled = true; } /// <summary> /// Catch unhandled exceptions not thrown by the main UI thread. /// The above AppUI_DispatcherUnhandledException method for DispatcherUnhandledException will only handle exceptions thrown by the main UI thread. /// Unhandled exceptions caught by this method typically terminate the runtime. /// </summary> void OnDispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e) { string errorMessage = string.Format("An application error occurred. If this error occurs again there seems to be a serious bug in the application, and you better close it.\n\nError:{0}\n\nDo you want to continue?\n(if you click Yes you will continue with your work, if you click No the application will close)", e.Exception.Message); //insert code to log exception here if (MessageBox.Show(errorMessage, "Application UnhandledException Error", MessageBoxButton.YesNoCancel, MessageBoxImage.Error) == MessageBoxResult.No) { if (MessageBox.Show("WARNING: The application will close. Any changes will not be saved!\nDo you really want to close it?", "Close the application!", MessageBoxButton.YesNoCancel, MessageBoxImage.Warning) == MessageBoxResult.Yes) { Application.Current.Shutdown(); } } e.Handled = true; } </code>