How To Destroy Thread in C# Language

Introduction

When you destroying threads , then you used to Abort() method. This is runtime abort  the thread throwing a Thread Aboard Exception, and this exception cannot be caught, it is send to finally block. 

Example

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading;

 

namespace how_to_destroy__Thread_in_c_sharp

{

    class Destroy_thread

    {

        public static void Child_Thread()

        {

            try

            {

                Console.WriteLine("Child Thread start:"); 

                // do some work, like counting to 10

                for (int counter = 0; counter <= 10; counter++)

                {

                    Thread.Sleep(500);               //interval between two counter

                    Console.WriteLine(counter);

                }

                Console.WriteLine("Child Thread Completed:");

 

            }

            catch (ThreadAbortException e)

            {

                Console.WriteLine("Thread Abort Exception:\n");

            }

            finally

            {

                Console.WriteLine("Could not catch the Thread Exception");

            }

 

        }

 

        static void Main(string[] args)

        {

            ThreadStart child_obj = new ThreadStart(Child_Thread);//create extending the Thread class

            Console.WriteLine("In Main : Creating the Child Thread");

            Thread childThread = new Thread(child_obj);

            childThread.Start();         // start child Thread

 

            Thread.Sleep(3000);         //stop the main Thread for some time

           

            Console.WriteLine("In Main: Abort the Child Thread\n");

            childThread.Abort();         //now abort the child

            Console.ReadKey();

        }

    }

}


Output


output.jpg

Ebook Download
View all
Learn
View all