Mega Code Archive

 
Categories / C# Tutorial / Thread
 

Interrupting a Thread

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();             }         }     } }