#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

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #877 – Unhandled Exceptions on Background Threads

  1. Garth N. Hammond says:

    This is a significant change from the .NET Framework versions 1.0 and 1.1, which provide a backstop for many unhandled exceptions — for example, unhandled exceptions in thread pool threads. See Change from Previous Versions later in this topic.

Leave 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 )

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

%d bloggers like this: