15.3. Preventing Silent Thread Termination
Problem
An exception thrown in a spawned worker thread will cause this thread to be silently terminated if the exception is unhandled. You need to make sure all exceptions are handled in all threads. If an exception happens in this new thread, you want to handle it and be notified of its occurrence.
Solution
You
must add exception handling to the method that you pass to the
ThreadStart delegate with a
try/catch, try/finally, or
try/catch/finally block. The code to do this is
shown here in bold:
using System;
using System.Threading;
public class MainThread
{
public void CreateNewThread( )
{
// Spawn new thread to do concurrent work
Thread newWorkerThread = new Thread(new ThreadStart(Worker.DoWork));
newWorkerThread.Start( );
}
}
public class Worker
{
// Method called by ThreadStart delegate to do concurrent work
public static void DoWork ( )
{
try
{
// Do thread work here
}
catch
{
// Handle thread exception here
// Do not re-throw exception
}
finally
{
// Do thread cleanup here
}
}
}Discussion
If an unhandled exception occurs in the main thread of an application, the main thread terminates, along with your entire application. An unhandled exception in a spawned worker thread, however, will terminate only that thread. This will happen without any visible warnings, and your application will continue to run as if nothing happened.
Simply wrapping an exception handler around the
Start method of the Thread class will not catch the exception on ...