
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
1022
|
Chapter 18: Threading and Synchronization
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 the newly created thread. The
Start method is called
within the context of the current thread, not the newly created thread. It also returns
immediately once the thread is launched, so it isn’t going to wait around for the
thread to finish. Therefore, the exception thrown in the new thread will not be
caught since it is not visible to any other threads.
Example 18-2. Preventing silent thread termination
using System;
using System.Threading;
public class MainThread
{
public void CreateNewThread( )
{
// Spawn new thread to do concurrent work.
Thread newWorkerThread = new Thread(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 ...