home *** CD-ROM | disk | FTP | other *** search
/ io Programmo 40 / IOPROG_40.ISO / SOFT / NETFrameworkSDK.exe / comsdk.cab / samples.exe / Threading / Thread / CS_Sample / StopJoin.cs < prev    next >
Encoding:
Text File  |  2000-06-23  |  1.3 KB  |  60 lines

  1. using System;
  2. using System.Threading;
  3.  
  4. public class Alpha
  5. {
  6.  
  7.     //    The method that will be called when the thread is started
  8.     public void Beta()
  9.     {
  10.         while (true)
  11.         {
  12.             Console.WriteLine("Alpha.Beta is running in its own thread.");
  13.             Thread.Sleep(0);
  14.         }
  15.     }
  16. };
  17.  
  18. public class Simple
  19. {
  20.     public static int Main(String[] args)
  21.     {
  22.         Console.WriteLine("Thread Stop Join Sample");
  23.         
  24.         Alpha        oAlpha        = new Alpha();
  25.  
  26.         //    Create the thread object, passing in the Alpha.Beta method
  27.         //    via a ThreadStart delegate
  28.         Thread        oThread1    = new Thread(new ThreadStart(oAlpha.Beta));
  29.  
  30.         //    Start the thread
  31.         oThread1.Start();
  32.  
  33.         //    Spin waiting for the started thread to become alive
  34.         while ((oThread1.ThreadState&ThreadState.Unstarted)!=0) ;
  35.         
  36.         //    Sleep. Allow oThread1 to do some work.
  37.         Thread.Sleep(100);
  38.         
  39.         //    Request that oThread1 be stopped
  40.         oThread1.Stop();
  41.         
  42.         //    Wait for the oThread1 to finish
  43.         oThread1.Join();
  44.         
  45.         Console.WriteLine();
  46.         Console.WriteLine("Alpha.Beta has finished");
  47.         
  48.         try 
  49.         {
  50.             Console.WriteLine("Try to restart the Alpha.Beta thread");
  51.             oThread1.Start();
  52.         }
  53.         catch (ThreadStateException) 
  54.         {
  55.             Console.Write("Cannot restart Alpha.Beta.  ");
  56.             Console.WriteLine("Expected since stopped threads cannot be restarted.");
  57.         }
  58.         return 0;
  59.     }
  60. }