Catching Thread Exceptions in C#

I have a Winforms app where I am performing asynchronous functions. I am using the delegate model and have threadsafe calls for updating my UI. My worker threads happen in an instance of another class, not the class that is the form.

I had the impression that the global Application.ThreadException event handler would catch exceptions that happened off on my working threads. This does not seem to be the case. The following code (as a console app) shows my problem and won’t catch the exception. The program executes as if nothing bad happened.

using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Windows.Forms;
using System.Runtime.Remoting.Messaging;
using System.Threading;
 
namespace BadThreadException
{
    class Program
    {
        delegate void WorkerDelegate(int input);
 
        static void Main(string[] args)
        {
            Application.ThreadException += new ThreadExceptionEventHandler(App_ThreadException);
 
            Worker mult = new Worker();
 
            AsyncCallback callback = new AsyncCallback(Finished);
 
            WorkerDelegate threadedWork = new WorkerDelegate(mult.DoSomethingImpressive);
 
            threadedWork.BeginInvoke(9, callback, null);
 
            Console.ReadKey();
        }
 
        static void Finished(IAsyncResult result)
        {
            Console.WriteLine("Done");
        }
 
        static void App_ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            Console.WriteLine("Got an error");
        }
    }
 
    class Worker
    {
        public void DoSomethingImpressive(int input)
        {
            throw new Exception("Ouch");
        }
    }
 
}

Well, I definitely need a solution to the problem, since exceptions definitely can happen off in my worker class. After some research, it turns out that you must call the EndInvode method on the delegate for the exception to bubble up. In my case, I wasn’t calling it because there was no return type. Now I understand why people frequently mention it is a best practice to always call EndInvoke, even if you don’t care about the return value (Doh!). The correct callback looks like this:

        static void Finished(IAsyncResult result)
        {
            AsyncResult ar = (AsyncResult)result;
            WorkerDelegate d = (WorkerDelegate)ar.AsyncDelegate;
 
            try
            {
                d.EndInvoke(ar);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Got an error on the callback");
            }
 
            Console.WriteLine("Done");
        }

I still haven’t discovered how/when the Application.ThreadException event handler gets called.