Friday, January 7, 2011

Global Exception Catching in WPF

AppDomain.UnhandledException
- all threads in the AppDomain
MSDN
Dispatcher.UnhandledException
- single specific UI dispatcher thread.
Application.DispatcherUnhandledException
- main UI dispatcher thread in your WPF application
MSDN
stackoverflow

Kent Boogaart
Application.DispatcherUnhandledException is only raised if the exception was raised on the UI thread, whereas AppDomain.UnhandledException is raised for exceptions that occur on background threads. Typically I attach to both and run similar handling code. The only difference is that DispatcherUnhandledException allows you to "recover" by setting Handled to true. In other words, you could prompt your user to see whether they'd like to attempt to continue running (and potentially avoid data loss).

Exceptions in Managed Threads

---

MSDN
If an exception is not handled on either a background user interface (UI) thread (a thread with its own Dispatcher) or a background worker thread (a thread without a Dispatcher), the exception is not forwarded to the main UI thread. Consequently, DispatcherUnhandledException is not raised. In these circumstances, you will need to write code to do the following:

- Handle exceptions on the background thread.
- Dispatch those exceptions to the main UI thread.
- Rethrow them on the main UI thread without handling them to allow DispatcherUnhandledException to be raised.

---

Example of Subscribing to AppDomain.CurrentDomain.UnhandledException


App.xaml.cs:

protected override void OnStartup(StartupEventArgs e)
{
AppDomain.CurrentDomain.UnhandledException += new
UnhandledExceptionEventHandler(this.AppDomainUnhandledExceptionHandler);
}

void AppDomainUnhandledExceptionHandler
(object sender, UnhandledExceptionEventArgs ea)
{
// handle the exception
}

No comments:

Post a Comment

comment: