Generically handling multi-threading exceptions in WPF

Fotografie de Pixabay pe Pexels.com

You have a WPF app and you just want to show a message whenever an exception is raised an not handled anywhere else in code. The first try is surely this:

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        DispatcherUanhandledException += App_DispatcherUnhandledException;
    }

    private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
    {
        MessageBox.Show(e.Exception.ToString());
    }
}

This works fine, as long as the exception isn’t raised in another thread.

To also handle those, unfortunately it’s not that easy. I only found this solution to work: catch the exception in the other thread and pass it to the main thread with BeginInvoke (note that with Invoke it still won’t go through the apps’ DispatcherUanhandledException event):

private void TryExecutingInAnotherThreadOrDispatchException()
{
    try
    {
        ExecutedInAnotherThread();
    }
    catch (Exception e)
    {
        Dispatcher.BeginInvoke((Action) delegate { throw e; });
    }
}

private void ExecutedInAnotherThread()
{
    throw new Exception("Testing the global handler.");
}

About Sorin Dolha

My passion is software development, but I also like physics.
This entry was posted in .NET, C#, WPF and tagged , , , . Bookmark the permalink.

Add a reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s