C# Source Code: Thread Interrupts Demonstration
[
Home
|
Contents
|
Search
|
Reply
| Previous | Next ]
C# Source Code
Thread Interrupts Demonstration
By:
Andrew Baker
Email (spam proof):
Email the originator of this post
Date:
Sunday, October 10, 2004
Hits:
1613
Category:
Threading/Asynchronous operations
Article:
When a thread is put to sleep, the thread goes into the WaitJoinSleep state. If the thread is in the sleeping state the only way to wake the thread (before the sleep times out) is to use the Interrupt() method. The Interrupt() method will place the thread back in the scheduling queue. See the example below: using System; using System.Threading; namespace vbUsers.Threading { ///
/// Thread Interrupt Demonstration ///
class InterruptDemo { public static Thread lazyProgrammer; public static Thread angryManager; [STAThread] static void Main(string[] args) { Console.WriteLine("Started..."); // Create threads lazyProgrammer = new Thread(new ThreadStart(LazyProgrammer)); angryManager = new Thread(new ThreadStart(AngryManager)); // Start Threads lazyProgrammer.Start(); // Wait for the programmer to get to work Thread.Sleep(10); angryManager.Start(); Console.WriteLine("Finished..."); // Pause Console.ReadLine(); } ///
/// Simulates a lazy programmer who is trying to get some sleep ///
public static void LazyProgrammer() { Console.WriteLine("Started Programmer..."); for(int i = 1; i < 5; i++) { try { // Try to get a couple secs, shut eye Console.WriteLine("{0} Programmer, 'zzzzz'", DateTime.Now.ToString("hh:mm:ss")); // Try to sleep for 20 secs Thread.Sleep(20000); // Print the time I was worken Console.WriteLine("{0} Programmer, 'Got away with it!!!'", DateTime.Now.ToString("hh:mm:ss")); } catch(System.Threading.ThreadInterruptedException ex) { // Manager caught me Console.WriteLine("{0} Programmer, 'Darn Busted Again!!!' (error " + ex.Message + ")", DateTime.Now.ToString("hh:mm:ss")); } } } ///
/// Simulates an angry manager who want his project finished - yesterday! ///
public static void AngryManager() { Console.WriteLine("Angry Manager..."); for(int i = 1; i < 6; i++) { // Check he's not asleep again Console.WriteLine("{0} Manager, 'Programmer is " + lazyProgrammer.ThreadState.ToString() + "'", DateTime.Now.ToString("hh:mm:ss")); if (lazyProgrammer.ThreadState == ThreadState.WaitSleepJoin) { // Wake that lazy programmer up! Console.WriteLine("{0} Manager, 'Wake up!!!'", DateTime.Now); lazyProgrammer.Interrupt(); } else { // He's awake Console.WriteLine("{0} Manager, 'Keep up the good work!'...", DateTime.Now.ToString("hh:mm:ss")); } // Managers meeting! Thread.Sleep(1000); } } } }
Terms and Conditions
Support this site
Download a trial version of the best FTP application on the internet