Advertisement
ivandrofly

Two Way Threads Signaling - C#

Mar 8th, 2014
264
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.33 KB | None | 0 0
  1. using System.Threading;
  2.  
  3. namespace Two_Way_Threads_Signaling
  4. {
  5.     internal class Program
  6.     {
  7.         private static EventWaitHandle handleA = new AutoResetEvent(false);
  8.         private static EventWaitHandle handleB = new AutoResetEvent(false);
  9.         private static volatile string message;
  10.  
  11.         private static void Main(string[] args)
  12.         {
  13.             new Thread(DoSomething).Start();
  14.  
  15.             handleA.WaitOne(); // wait till DoSomething is ready to reply
  16.             message = "Hello";
  17.             handleB.Set(); // Indicate DoSomething it can proceed
  18.  
  19.             handleA.WaitOne();// wait till DoSomething is ready to reply
  20.             message = "Goo morning";
  21.             handleB.Set();
  22.  
  23.             handleB.WaitOne();  // wait till DoSomething is ready to reply
  24.             message = "How are you";
  25.             handleB.Set();
  26.  
  27.             handleA.WaitOne(); // wait till DoSomething is ready to reply
  28.             message = "Exit";
  29.             handleB.Set();
  30.         }
  31.  
  32.         private static void DoSomething()
  33.         {
  34.             while (true)
  35.             {
  36.                 handleA.Set(); // indicate DoSomething is ready
  37.                 handleB.WaitOne(); // wait for getting a message
  38.                 if (message == "exit")
  39.                     return;
  40.             }
  41.         }
  42.     }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement