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






using System;
using System.Threading;

public class Interrupt {
    public static Thread sleeper;
    public static Thread worker;

    public static void Main() {
        sleeper = new Thread(new ThreadStart(SleepingThread));
        worker = new Thread(new ThreadStart(AwakeTheThread));

        sleeper.Start();
        worker.Start();

    }
    public static void SleepingThread() {
        for (int i = 1; i < 10; i++) {
            Console.Write(i + " ");
            Console.WriteLine("Going to sleep at: " + i);
            Thread.Sleep(20);
           
        }
    }

    public static void AwakeTheThread() {
        for (int i = 11; i < 20; i++) {
            Console.Write(i + " ");
            if (sleeper.ThreadState == System.Threading.ThreadState.WaitSleepJoin) {
                Console.WriteLine("Interrupting the sleeping thread");
                sleeper.Interrupt();
            }
        }
    }
}








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