Click here to Skip to main content
15,949,741 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi everyone,

I'm not fully understanding the EventWaitHandle class and the while() within the producer consumer queue:
C#
Queue<string> que = new Queue<string>();
EventWaitHandle wh = new AutoResetEvent(false);
object sync = new object();

private void job(string task)
{
  lock(sync)
  {
    queue.Enqueue(task);
  }
  wh.Set();
}

private void worker()
{
  while(true)
  {
     string copyTask = "";

     lock(sync)
     {
       if(queue.Count > 0)
       {
         copyTask = queue.Dequeue();
       }
       
      if(copyTask != "")
      {
          // process data...
      }
      else
        wh.WaitOne();
  }
}
</string></string>

My question is: "if" the wh.WaitOne() sends a signal to wh.Set() notifying job() that it's ready to process data why is the while() necessary? Does the wh.WaitOne() stop the while() loop and put it to sleep? Or does it put the Thread that worker() is running on to sleep?

I've read and done a few tutorials on this and I'm still not clearly understanding what's going on. Can someone please explain to me what's happening here?

Thank in advance!
-Donald
Posted
Updated 18-Mar-11 20:08pm
v2

1 solution

See the full source code and explanation in my Tips/Tricks article: Simple Blocking Queue for Thread Communication and Inter-thread Invocation[^]. It solves exactly the same problem, only in a cultured way, using generics.

You're very confused with threading, not just WaitOne. When a thread is calling a blocking code such as WaitOne it is "sleeping" using zero CPU time. The thread simply switched of and never scheduled for execution again until it is "waken up". EventWaitHandle.Set of the same instance makes the thread in wait state wake up. There is no loop at all. That you probably have in mind is called "spin-wait" and is the absolute evil.

—SA
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900