#877 – Unhandled Exceptions on Background Threads

Unhandled exceptions that originate on background (or worker) threads will also terminate an application, just like unhandled exceptions that originate on the main thread.

In the example below, we execute the DoSomethingInBackground method on a background thread.  Execution continues in parallel on the main thread, while the background thread is running.

        static void Main(string[] args)
        {
            Thread worker = new Thread(DoSomethingInBackground);
            worker.Start();

            // Continue here immediately after launching background
            // worker
            Console.WriteLine("I've launched the worker!");

            while (true)
                Console.WriteLine(Console.ReadLine());
        }

        static void DoSomethingInBackground()
        {
            Console.WriteLine("DoSomething start");
            Thread.Sleep(3000);
            Console.WriteLine("DoSomething middle");
            Thread.Sleep(3000);
            throw new Exception("Oh no !");
            Console.WriteLine("DoSomething end");
        }

When the background thread throws an exception and we don’t handle it, the entire application (rather than just the background thread) is terminated.

877-001

Advertisements