#877 – Unhandled Exceptions on Background Threads
July 1, 2013 1 Comment
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.
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.