22.2 Pausing and Resuming a Thread

 <  Day Day Up  >  

You want to temporarily prevent a thread from running for some period of time.


Technique

The technique depends on whether the thread to be suspended also happens to be the one deciding on the suspension.

If a thread decides that it itself should wait for a set period of time, then it can simply put itself to sleep by calling the static Thread.Sleep() method:

 
 Thread.Sleep(500); 

Sleep() takes an int parameter that indicates the time in milliseconds for which the thread should sleep. The thread simply relinquishes all its timeslots for this length of time, thus consuming virtually no CPU time.

If, on the other hand, one thread decides that another thread should pause, it can call the (instance) method, Thread.Suspend() :

 
 // assume workerThread is a thread reference. workerThread.Suspend(); 

When the controlling thread wants to reactivate the suspended thread, it calls Thread.Resume() :

 
 workerThread.Resume(); 

Comments

Although these techniques represent the simplest ways to suspend a thread, we present them here only for completeness. Sleeping a thread for an arbitrary period of time in the ways shown here is fairly limited in usefulness other than for debugging purposes. Usually, the reason for suspending threads concerns thread or variable access synchronization or the need to call some method regularly at fixed time intervals. For these purposes, there are more powerful thread synchronization and timer classes available, which we discuss later in the chapter.

 <  Day Day Up  >  


Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net