Wednesday, February 02, 2005

Interrupting a Thread

When a thread is in the sleep mode, it goes to the WaitSleepJoin state.

The only way for that thread to “wake up” before its timeout expiures is to use the Interrupt() method.

When a calling thread interrupts a sleeping threat, a ThreadInterruptedException is thrown in the interrupted thread.

This is a sample code from Microsoft's MSDN


while (!sleepSwitch)
   {
   // Use SpinWait instead of Sleep to demonstrate the
   // effect of calling Interrupt on a running thread.
   Thread.SpinWait(10000000);
   }
try
   {
   Console.WriteLine("newThread going to sleep.");
   // When newThread goes to sleep (blocks),
   // it is immediately
   // woken up by a ThreadInterruptedException.
   Thread.Sleep(TimeSpan.FromMilliseconds(1));
   Console.WriteLine("newThred awaken");
   }
catch (ThreadInterruptedException )
   {
   Console.WriteLine("newThread cannot go to sleep - " +
                     "interrupted by main thread - ");
   }





0 Comments:

Post a Comment

<< Home