A book as the following example and explains that you won’t see the line “DoWork has ended”:
…because the thread was aborted
while DoWork was executing
Thread.Sleep
That makes sense, but what is odd is that if you change the first sleep to 6000 to give the DoWork thread time to get done with its 5000 sleep, then the DoWork thread will print “DoWork has ended” but this is after the DoWork thread has been aborted, so if the DoWork thread has been aborted at that point, what thread is the line that prints “DoWork has ended” running in? (it seems to be running at that point in the aborted thread)
using System;
using System.Threading;
namespace TestThreading838
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("MAIN THREAD started.");
Thread DoWorkThread = new Thread(new ThreadStart(DoWork));
DoWorkThread.Start();
Thread.Sleep(1000); //if you change this to 6000 you see "DoWork has ended."
DoWorkThread.Abort();
Console.WriteLine("MAIN THREAD ending...");
Thread.Sleep(6000);
Console.WriteLine("MAIN THREAD ended.");
Console.ReadLine();
}
public static void DoWork()
{
Console.WriteLine("DoWork is running.");
try
{
Thread.Sleep(5000);
}
catch (ThreadAbortException ex)
{
Console.WriteLine("DoWork was aborted.");
}
finally
{
Console.WriteLine("DoWork cleaning up after being aborted.");
}
Console.WriteLine("DoWork has ended."); //never shown
}
}
}
If you change the first sleep to 6000, then the secondary thread finishes everything it needs to do before you abort it – it’s not really aborted, because you’ve just called
Aborton a thread which was already dead. Notice that “DoWork was aborted” won’t be printed…Try printing out
DoWorkThread.ThreadStatebefore you callAbort– I’m pretty sure you’ll see it’s “Stopped”.