Joydip Kanjilal
Contributor

My two cents on the Thread.Abort and Thread.Interrupt methods

opinion
Aug 10, 20164 mins
Software Development

Proper synchronization constructs, structured and deterministic code flow will help you avoid Thread.Abort or Thread.Interrupt methods and terminate threads gracefully

In C#, you might often need to release a thread that has been blocked. To achieve this, there are two methods that you can take advantage of. These include the Thread.Abort and Thread.Interrupt methods.

What does the Thread.Abort method do?

To terminate a thread you can take advantage of the Abort method of the Thread class. Note that to initiate the process of terminating a thread, the Abort method of the Thread class when invoked, raises a ThreadAbortException in the thread on which it has been called. It should be noted that you can take advantage of the Abort method of the Thread class to terminate even a non-blocked thread. If the thread that is being interrupted is in a waiting state, it wakes it up and then causes a ThreadInterruptedException to be thrown. Similarly, if you call the Thread.Abort method on a thread that is in waiting state, the runtime wakes the thread up and then throws a ThreadAbortException.

You can catch the ThreadAbortException in the catch block. However, if you don’t call the ResetAbort method, this exception will be re-thrown at the end of the catch block. The call to the ResetAbort method will prevent the ThreadAbortException from being re-throw at the end of the catch block. Contrary to how the Thread.Inturrupt methods works, if the thread on which the Thread.Abort method is called is not blocked, the Thread.Abort method throws a ThreadAbortException on the thread.

In most cases (unless you would like to shut down the application domain after a thread is aborted), you don’t need to use this method at all. Note that the Response.Redirect method in ASP.Net throws a ThreadAbortException.

What is the purpose of the Thread.Interrupt method?

You can use the Thread.Interrupt method to interrupt a thread that is in WaitSleepJoin state. However, none of these approaches (Thread.Abort or Thread.Interrupt method calls) are thread safe. While the Thread.Abort method throws a ThreadAbortException, the Thread.Interrupt method throws a ThreadInterruptException. Essentially, a call to the Thread.Interrupt method interrupts the thread and throws a ThreadInterruptedException to interrupt the thread inside of a blocking call. You should handle this exception in your code failing which the runtime would stop the thread on which the Thread.Interrupt method has been called. It should be noted that a call to Thread.Interrupt doesn’t interrupt a thread that is executing unmanaged code.

Consider the following code listing that illustrates how Thread.Interrupt method can be called forcibly to interrupt a thread.

static void Main(string[] args)

       {

           Thread thread = new Thread(ThreadMethod);

           thread.Start();

           thread.Interrupt();

           Console.Read();

       }

       private static void ThreadMethod()

       {

           try

           {

               Thread.Sleep(Timeout.Infinite);

           }

           catch (ThreadInterruptedException)

           {

             Console.Write("ThreadInterruptedException has been called forcibly.");

           }

       }

When the above program is executed, the message “ThreadInterruptedException has been called forcibly” will be displayed in the console.

What happens if the thread that is being interrupted is not blocked? I you make a call to Thread.Interrupt on a thread that is not blocked, the thread would continue to execute till the time it is blocked next. In most cases, you don’t need to use Thread.Interrupt at all. You can achieve the same using signalling constructs or cancellation tokens.

Should I use the Thread.Abort or the Thread.Interrupt method?

So, when should I use Thread.Abort vs Thread.Interrupt methods in my program? If I need to cancel a certain operation, which of these methods should I use? My honest answer is that you should never use either of these methods to terminate a thread. It is advisable not to use Thread.Abort or Thread.Interrupt methods to terminate a thread – you should rather take advantage of synchronization objects (like, WaitHandles or Semaphores) and perform a graceful termination of the threads you are using. The following code snippet illustrates how you can take advantage of a WaitHandle to allow a thread to stop gracefully.

private void ThreadMethod()

{

   while(!manualResetEventObject.WaitOne(TimeSpan.FromMilliseconds(100)))

   {

       //Write your code here

   }

}

As an alternative approach to terminate a thread gracefully, you can also take advantage of a volatile “boolean” variable. You can then set this variable in the UI thread on some user activity (assume that the user has clicked on the “Cancel” button in the UI to terminate the thread) and then check the value of the variable from time to time in the Worker thread to see if the variable has been set (maybe a value of “false” to indicate termination of the thread) in the user interface.

Joydip Kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author