Jim's Software |  Jim and Katrin

Random development notes

WPF Worker Thread Exceptions

6/23/2008  9:37 PM

What if you want to do global exception handling with worker threads? My scenario involves data methods that may be called synchronously, on the UI thread, or asynchronously on a worker. I would like to use the same global exception handling for both.

The problem with this scenario is that unhandled exceptions in the worker thread may cause the application to terminate; there's no handler you can use or flag you can set to prevent this.

One way of handling this is explained as a side note in MSDN's Application.DispatcherUnhandledException documentation:

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

I guess they thought the code was too obvious to bother providing an example...

That list is mentioned in the MSDN forums, where an example was promised, but not delivered.

try
{
    . . . 
}
catch (Exception ex)
{
    . . . 

    // Are we not on the main UI thread?
    if (!Application.Current.Dispatcher.CheckAccess())
    {
        // Unhandled exceptions on worker threads will halt the application. We want to
        // use our global exception handler(s), so dispatch or "forward" to the UI thread.
        Application.Current.Dispatcher.Invoke(
            System.Windows.Threading.DispatcherPriority.Normal,
            new Action<Exception>(WorkerThreadException), ex);
    }
    else
    {
        throw;  // Already on UI thread; just rethrow the exception to global handlers
    }
}

The WorkerThreadException method simply re-throws the exception on the UI thread, where it is handled by any global exception handlers that have been defined:

private static void WorkerThreadException(Exception ex)
{
    throw ex;
}
Comments:

Post a Comment





<< Home