Thursday, December 9, 2010

How to Destroy Threads in c# Console Application.

If the thread is required to be destroyed, the thread.Abort ( ) method will allow you to accomplish the task. The runtime aborts the thread by throwing a ThreadAbortException. This exception cannot be caught. The finally block is present in the method; the runtime will send the control to it.

Following example is destroy threads:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Threadsample
{
    class BasicThreadApp

    {
      public static void ChildThreadCall()
      {
          try
          {
              Console.WriteLine("Child thread started:");
              Console.WriteLine("Child thread - counting to 10:");
              for (int i = 0; i <= 10; i++)
              {
                  Thread.Sleep(500);
                  Console.Write("{0}...", i);
              }
              Console.WriteLine("Child thread finished:");
          }
          catch (ThreadAbortException )
          {
              Console.WriteLine("Exception");
          }
          finally
          {
              Console.WriteLine("Child thread -unable to catch the exception:");
          }
      }
        public static void Main()
        {
            ThreadStart ChildRef = new ThreadStart(ChildThreadCall);
            Console.WriteLine("Main - Creating Child thread:");

            Thread ChildThread = new Thread(ChildRef);
            ChildThread.Start();

            //Give the Child thread time to start.
            Console.WriteLine("Main - Sleeping for 2 seconds:");
            Thread.Sleep(2000);

            Console.WriteLine("\nMain - Aborting Child thread:");
            ChildThread.Abort();
            Console.ReadLine();
        
        }
    }
}

Output is shows below:



Note: - The Main ( ) Method pauses for two seconds to make sure that the runtime has had time to start the worker thread. When started, the worker thread starts counting to ten, pausing for a second in between each number. When the Main ( ) method resumes execution after its two-second pause, it aborts the worker thread. Notice, the finally block is executed after the abort.

1 comment:

Rajeev said...

All information is well defined,,

Thanks

Recent Posts