Click here to Skip to main content
15,121,030 members
Articles / Programming Languages / C#
Posted 7 Aug 2008


72 bookmarked

SafeThread - Prevent Unhandled Exceptions in Secondary Threads

Rate me:
Please Sign up or sign in to vote.
4.76/5 (33 votes)
19 Aug 2008CPOL6 min read
Prevent unhandled exceptions in secondary threads, using SafeThread
Image 1


Unhandled exceptions can occur in almost any program. When they happen in a secondary (worker) thread, they can kill the application - or worse, be ignored! Prevent unhandled exceptions in secondary threads by using SafeThread.



While researching the behavior of unhandled exceptions in .NET 2.0 applications for the CALM project, one of the more surprising and frustrating findings was the way in which unhandled exceptions in secondary threads tend to kill the application or be completely ignored! Unhandled exceptions in secondary threads (threads that you create explicitly) will kill the application, even if you have an unhandled exception event handler (plus the contextual information, i.e., which thread, is lost). Unhandled exceptions in worker (ThreadPool) threads and Timer threads, in particular, are ignored by the Common Language Runtime (CLR). These threads just die, with no unhandled-exception event to trap, no warning to the user, nothing. Obviously, in production applications, this is unacceptable (mis-)behavior!


Thus, the SafeThread class was created. SafeThread wraps a regular CLR Thread, but executes the method delegate inside a try-catch block that emits an event when an unhandled exception occurs. Developers can use this event to clean up after the thread, classify the kind of exceptions, or even launch a new thread. For certain kinds of threaded operations like "heartbeat" operations, this is valuable and necessary for a robust application.

The premise behind SafeThread is fairly simple. Since threads rely on a method delegate for execution, all we need to do is wrap the execution of the delegate in a try-catch block and emit an event if we catch an exception. The base Thread class supports a single-parameter delegate and a no-parameters delegate, so SafeThread mimics these constructors. In addition, SafeThread supports the new dynamic delegates (also known as, anonymous methods) for additional convenience. Finally, to complete the facade, SafeThread implements all of the public methods and properties of the Thread class. SafeThread also provides a ThreadCompleted event to signal when processing is completed.

SafeThread Implementation

Clearly, it would be best if SafeThread could inherit from Thread, but this is not possible since the Thread class is sealed (MustInherit in VB.NET terminology). The next-best solution would be for SafeThread to implement a common interface for threads (such as IThread), but alas, .NET does not have this either. So, the best we can do is re-implement the interface and wrap a Thread object. Note that this does present a few issues in that some properties and methods of SafeThread are not valid unless the wrapped Thread already exists, as the wrapped Thread object is not created until the Start method is called.

SafeThread Usage

SafeThread may be used exactly as the CLR Thread class, e.g., using a ThreadStart, with the addition of a ThreadException event and a flag to control whether calling Abort on the thread is reported as an exception or not.

SafeThread thrd = new SafeThread(new ThreadStart(this.threadRunner));
thrd.ShouldReportThreadAbort = true;
thrd.ThreadException += 
     new ThreadThrewExceptionHandler(thrd_ThreadException);
thrd.ThreadCompleted += 
     new ThreadCompletedHandler(thrd_ThreadCompleted);

In addition to ThreadStart and ParameterizedThreadStart, SafeThread also offers a SimpleDelegate option, which can be used with any void no-argument method:

SafeThread thrd = new SafeThread((SimpleDelegate)this.threadRunner));
thrd.ShouldReportThreadAbort = true;
thrd.ThreadException += 
     new ThreadThrewExceptionHandler(thrd_ThreadException);
thrd.ThreadCompleted += 
     new ThreadCompletedHandler(thrd_ThreadCompleted);

SimpleDelegate can also be used with an anonymous method:

SafeThread thrd = new SafeThread((SimpleDelegate) 
           delegate { this.threadRunner(); });
thrd.ShouldReportThreadAbort = true;
thrd.ThreadException += 
     new ThreadThrewExceptionHandler(thrd_ThreadException);
thrd.ThreadCompleted += 
     new ThreadCompletedHandler(thrd_ThreadCompleted);

The ThreadException handler is passed the SafeThread object that threw the exception, and also the Exception that was thrown:

void thrd_ThreadException(SafeThread thrd, Exception ex)
    //do something here, like restart the thread 

The ThreadComleted handler is passed the SafeThread object that completed processing, along with a bool to say whether processing was terminated due to an exception or not, and the offending Exception or null (Nothing in VB.NET terminology) if processing completed successfully.

void thrd_ThreadCompleted(SafeThread thrd, bool hadException, Exception ex)
    if (hadException)
        //the thread terminated early due to an unhandled exception in ex
        //the thread completed successfully

SafeThread Demo Application

The SafeThread demo application is both contrived and silly: each SafeThread created periodically pulses the animation of the Start SafeThread button in a circle. Each SafeThread created will pulse the animation 99% of the time, and 1% of the time will throw an unhandled divide-by-zero exception. If the SafeThread survives 100 iterations, it completes successfully and emits a ThreadCompleted event. The ListBox shows what is happening with each SafeThread.

To use the SafeThread demo application, build and/or run it. Click the Start SafeThread button several times - the more SafeThread objects created, the faster the button will move in a circle. Click the Stop SafeThread button to end the SafeThread objects in the order created. Click a ListBox item to see the full item text in a MessageBox. All of the SafeThread objects are ended when the application is closed.

UnsafeThread Demo Application

Just for fun, and to address some good points raised by Daniel Grunwald in the comments below, I have added an "unsafe" thread demo application to the article to better illustrate what happens without exception trapping or SafeThread. Click the Start Unsafe Thread button to launch a regular CLR Thread that throws an unhandled divide-by-zero exception, and note that with no protection at all, what you get is the send-a-debug-report-to-Microsoft dialog, and the application dies. Run the demo again, but this time, first check the Use Unhandled Exception Handlers checkbox and then click the Start Unsafe Thread button. Now, we get a message box, courtesy of the AppDomain.UnhandledException event... and then, we get the send-a-debug-report-to-Microsoft dialog, and the application dies.

This illustrates several issues with just using the System.AppDomain.CurrentDomain.UnhandledException event handler to trap exceptions in 'pure' secondary threads (i.e., not worker threads or Timer threads):

  • There is not enough contextual information available in the event handler to know which thread caused the problem; the sender argument is the application, not the thread.
  • By the time the unhandled exception reaches the event handler, it is too late to do anything about it - the application is already terminating!
  • No matter what you do, the application is going to die.
  • Finally - and this is the thing I dislike the most about this mechanism - after your unhandled exception event handler finishes, the dreaded send-a-debug-report-to-Microsoft dialog appears!


SafeThread has a few more properties of interest:

  • SafeThread has a Name property which is passed to the underlying CLR thread on Start. The default CLR thread Name is SafeThread#XXX where XXX is the HashCode of the CLR Thread object.
  • SafeThread remembers its start argument in the ThreadStartArg property, when used with a ParameterizedThreadStart.
  • SafeThread provides a generic Tag object property, which is useful for remembering arbitrary information about the thread.
  • SafeThread provides a LastException property, which records the last exception captured by the SafeThread.


Note that the behavior of unhandled exceptions in secondary threads changed in .NET 2.0. In .NET 1.1, an unhandled exception in a worker (ThreadPool) thread (but not a Timer thread) would be captured by the AppDomain's UnhandledException event. Microsoft provides a backwards-compatibility option in the application configuration file:

    <legacyUnhandledExceptionPolicy enabled=&quot;1&quot;/>

See MSDN for details.

Future Directions

A SafeThreadPool would be a logical component to use the SafeThread class, as would a SafeTimer class. These may be covered in future article updates.

Revision History

  • 08-07-2008
    • Initial version of article published
  • 08-08-2008
    • UnsafeThread demo and source added, to show what happens without SafeThread
    • UnsafeThread demo description section added
    • Edited the Background section to clarify the different behavior of the secondary thread types
    • Edited the Notes section to clarify the purpose of the legacy-compatibility option
    • Extra License section removed
  • 08-17-2008
    • SafeThread class updated to emit the ThreadCompleted event
    • SafeThreadDemo application updated to use ParameterizedThreadStart to pass a time-to-live argument to the threadRunner method, and to hook the ThreadCompleted event and update the text in the ListBox
    • SafeThreadDemo application corrected to remove completed SafeThreads from the threads collection


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Steven A. Lowe
Technical Lead ThoughtWorks
United States United States
Steven A. Lowe is a consultant, software developer, inventor, entrepreneur, author, musician, and lover of puns. He ran an innovative custom software development company for nearly a decade before joining ThoughtWorks as a Principal Consultant in 2014. He admits to being the author of "From Burnout to Bonfire" and a willing participant in the band Noise in the Basement, but neither confirms nor denies being the science-fiction author Steven Ayel.

Comments and Discussions

Questionroadmap Pin
kiquenet.com16-Nov-15 22:51
professionalkiquenet.com16-Nov-15 22:51 
Generalnice article Pin
BillW3325-Mar-11 6:42
professionalBillW3325-Mar-11 6:42 
GeneralApplication.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);//sometimes it helps Pin
zzluka25-Nov-09 10:56
Memberzzluka25-Nov-09 10:56 
GeneralUnsafe threads — omiting "Send report" dialog. Pin
modosansreves28-Jun-09 13:15
Membermodosansreves28-Jun-09 13:15 
GeneralRe: Unsafe threads — omiting "Send report" dialog. Pin
Steven A. Lowe29-Jun-09 4:58
MemberSteven A. Lowe29-Jun-09 4:58 
GeneralRe: Unsafe threads — omiting "Send report" dialog. Pin
modosansreves29-Jun-09 10:46
Membermodosansreves29-Jun-09 10:46 
GeneralRe: Unsafe threads — omiting "Send report" dialog. Pin
Steven A. Lowe29-Jun-09 10:56
MemberSteven A. Lowe29-Jun-09 10:56 
GeneralLittle bug Pin
marsever12-Feb-09 5:32
Membermarsever12-Feb-09 5:32 
GeneralGreat Job!!! Pin
Member 21135356-Feb-09 10:39
MemberMember 21135356-Feb-09 10:39 
GeneralRe: Great Job!!! Pin
Steven A. Lowe6-Feb-09 17:46
MemberSteven A. Lowe6-Feb-09 17:46 
GeneralSafeThread for VB Pin
gstarr0117-Dec-08 5:49
Membergstarr0117-Dec-08 5:49 
GeneralRe: SafeThread for VB Pin
Steven A. Lowe17-Dec-08 7:36
MemberSteven A. Lowe17-Dec-08 7:36 
GeneralRe: SafeThread for VB Pin
gstarr0117-Dec-08 8:05
Membergstarr0117-Dec-08 8:05 
GeneralRe: SafeThread for VB Pin
Steven A. Lowe17-Dec-08 8:14
MemberSteven A. Lowe17-Dec-08 8:14 
GeneralRe: SafeThread for VB Pin
gstarr0129-Dec-08 10:44
Membergstarr0129-Dec-08 10:44 
GeneralRe: SafeThread for VB Pin
Steven A. Lowe29-Dec-08 11:00
MemberSteven A. Lowe29-Dec-08 11:00 
GeneralRe: SafeThread for VB Pin
Steven A. Lowe29-Dec-08 11:01
MemberSteven A. Lowe29-Dec-08 11:01 
GeneralRe: SafeThread for VB Pin
modosansreves28-Jun-09 23:11
Membermodosansreves28-Jun-09 23:11 
GeneralRe: SafeThread for VB Pin
Steven A. Lowe29-Jun-09 5:01
MemberSteven A. Lowe29-Jun-09 5:01 
GeneralGreat stuff. Pin
Ghost827-Oct-08 2:00
MemberGhost827-Oct-08 2:00 
GeneralRe: Great stuff. Pin
Steven A. Lowe7-Oct-08 5:34
MemberSteven A. Lowe7-Oct-08 5:34 
QuestionstartTarget function has a bug ?? Pin
leegool19-Aug-08 23:08
Memberleegool19-Aug-08 23:08 
AnswerRe: startTarget function has a bug ?? Pin
Steven A. Lowe20-Aug-08 7:08
MemberSteven A. Lowe20-Aug-08 7:08 
QuestionGood Coding, Anyone? Pin
merlin9818-Aug-08 4:55
professionalmerlin9818-Aug-08 4:55 
AnswerRe: Good Coding, Anyone? Pin
Steven A. Lowe8-Aug-08 5:37
MemberSteven A. Lowe8-Aug-08 5:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.