Advertisement
ivandrofly

Create and Terminate Threads

Jan 13th, 2014
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.02 KB | None | 0 0
  1. C#
  2.  
  3. using System;
  4. using System.Threading;
  5.  
  6. public class Worker
  7. {
  8.     // This method will be called when the thread is started.
  9.     public void DoWork()
  10.     {
  11.         while (!_shouldStop)
  12.         {
  13.             Console.WriteLine("worker thread: working...");
  14.         }
  15.         Console.WriteLine("worker thread: terminating gracefully.");
  16.     }
  17.     public void RequestStop()
  18.     {
  19.         _shouldStop = true;
  20.     }
  21.     // Volatile is used as hint to the compiler that this data
  22.     // member will be accessed by multiple threads.
  23.     private volatile bool _shouldStop;
  24. }
  25.  
  26. public class WorkerThreadExample
  27. {
  28.     static void Main()
  29.     {
  30.         // Create the thread object. This does not start the thread.
  31.         Worker workerObject = new Worker();
  32.         Thread workerThread = new Thread(workerObject.DoWork);
  33.  
  34.         // Start the worker thread.
  35.         workerThread.Start();
  36.         Console.WriteLine("main thread: Starting worker thread...");
  37.  
  38.         // Loop until worker thread activates.
  39.         while (!workerThread.IsAlive);
  40.  
  41.         // Put the main thread to sleep for 1 millisecond to
  42.         // allow the worker thread to do some work:
  43.         Thread.Sleep(1);
  44.  
  45.         // Request that the worker thread stop itself:
  46.         workerObject.RequestStop();
  47.  
  48.         // Use the Join method to block the current thread  
  49.         // until the object's thread terminates.
  50.         workerThread.Join();
  51.         Console.WriteLine("main thread: Worker thread has terminated.");
  52.     }
  53. }
  54.  
  55. Here is the output:
  56.  
  57. main thread: starting worker thread...
  58. worker thread: working...
  59. worker thread: working...
  60. worker thread: working...
  61. worker thread: working...
  62. worker thread: working...
  63. worker thread: working...
  64. worker thread: working...
  65. worker thread: working...
  66. worker thread: working...
  67. worker thread: working...
  68. worker thread: working...
  69. worker thread: terminating gracefully...
  70. main thread: worker thread has terminated
  71. Source:
  72. http://msdn.microsoft.com/en-us/library/7a2f3ay4%28v=vs.90%29.aspx
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement