Tutorial :How can you abort a thread and have code still executing in that thread?


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 Abort on a thread which was already dead. Notice that "DoWork was aborted" won't be printed...

Try printing out DoWorkThread.ThreadState before you call Abort - I'm pretty sure you'll see it's "Stopped".


"DoWork has ended" is running on the second Thread (DoWorkThread).

    DoWorkThread.Start(); //Run the thread      Thread.Sleep(6000); //Let the thread run for 6sec so "DoWork has ended" will be displayed      DoWorkThread.Abort();  


The ThreadAbortException is automatically rethrown unless you call Thread.ResetAbort(). So after it is caught the system rethrows it and the finally is executed but at that point it becomes an unhandled exception so the "DoWork has ended." is never printed.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »