Interrupting Threads : Thread Interrupt « Thread « C# / CSharp Tutorial






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


    class Tester
    {
        static void Main()
        {
            Thread[] myThreads = 
             {
                 new Thread( new ThreadStart(Decrementer) ),
                 new Thread( new ThreadStart(Incrementer) ),
                 new Thread( new ThreadStart(Decrementer) ), 
                 new Thread( new ThreadStart(Incrementer) ) 
             };
            int ctr = 1;
            foreach (Thread myThread in myThreads)
            {
                myThread.IsBackground = true;
                myThread.Start();
                myThread.Name = "Thread" + ctr.ToString();
                ctr++;
                Console.WriteLine("Started thread {0}",myThread.Name);
                Thread.Sleep(50);
            }
            myThreads[0].Interrupt();
            myThreads[1].Abort();
            foreach (Thread myThread in myThreads)
            {
                myThread.Join();
            }
        }
        public static void Decrementer()
        {
            for (int i = 10; i >= 0; i--){
                Console.WriteLine("Thread {0}. Decrementer: {1}",Thread.CurrentThread.Name, i);
                Thread.Sleep(1);
            }
            Console.WriteLine("Thread {0} Exiting. ",Thread.CurrentThread.Name);
        }
        public static void Incrementer()
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("Thread {0}. Incrementer: {1}",Thread.CurrentThread.Name, i);
                Thread.Sleep(1);
            }
            Console.WriteLine("Thread {0} Exiting. ",Thread.CurrentThread.Name);
         }
    }








20.6.Thread Interrupt
20.6.1.Sleep Interupt Threads
20.6.2.Interrupting a Thread
20.6.3.Interrupting Threads