Thread.Abort and Thread.Join

Published on Friday, June 3, 2011
c#

There was no Thread.Join method in .NET 1.1, it is only available in .NET 2.0 and later.

Thread.Join()

Blocks the calling thread until a thread terminates, while continuing to perform standard COM and SendMessage pumping.

Thread.Abort()

Raises a ThreadAbortException in the thread on which it is invoked, to begin the process of terminating the thread. Calling this method usually terminates the thread.

When Thread.Abort is called, a ThreadAbortException will be thrown. Normally you should handle the ThreadAbortException if there is anything specific you must do when the thread is being aborted.

In .NET 2.0 and later, if a finally block is executing, ThreadAbortException will be pended until process leaves the finally block. This is different with in .NET 1.x: in NET 1.x, the abort will be exception whatever.

So Thread.Abort can not guarantee to abort thread immediately in .NET 2.0 and later. So one way is that you wait until the thread is truly finished executing, then you have to call Thread.Join to wait until all of the code in the ThreadAbortException exception handler is finished.

The following is a sample which is reference to the book "Accelerated C#":


using System;
using System.Threading;

public class Sample
{

private static void myProcess()
{
ulong counter = 0;
while( true ) 
{
try 
{
Console.WriteLine( "{0}", counter++ );
}
catch( ThreadAbortException ) 
{
// Attempt to swallow the exception and continue.
Console.WriteLine("Abort! " );
}
}
}

static void Main() 
{

Thread newThread = new Thread( new ThreadStart(Sample.myProcess) );

newThread.Start();

Thread.Sleep( 1000 );

// Abort the thread.
newThread.Abort();

// Wait for thread to finish.
newThread.Join();
}

}