title: Producer Consumer With AutoResetEvent
body: <p>I'm trying to use the producer consumer pattern to process and save some data. I'm using AutoResetEvent for signalling between the two therads here is the code I have </p>
  
  <p>Here is the producer function</p>
  
  <pre><code> public Results[] Evaluate()
      {
          processingComplete = false;
          resultQueue.Clear();
          for (int i = 0; i &lt; data.Length; ++i)
              {
                  if (saveThread.ThreadState == ThreadState.Unstarted)
                      saveThread.Start();
                 //-....
                 //Process data 
                 // 
                  lock (lockobject)
                  {
                      resultQueue.Enqueue(result);
                  }
  
                  signal.Set();
              }
              processingComplete = true;
          }
  </code></pre>
  
  <p>And here is the consumer function</p>
  
  <pre><code>   private void SaveResults()
      {
          Model dataAccess = new Model();
  
          while (!processingComplete || resultQueue.Count &gt; 0)
          {
              if (resultQueue.Count == 0)
                  signal.WaitOne();
              ModelResults result;
              lock (lockobject)
  
              {
                  result = resultQueue.Dequeue();
              }
              dataAccess.Save(result);
          }
          SaveCompleteSignal.Set();
      }
  </code></pre>
  
  <p>So my issue is sometimes resultQueue.Dequeue() throws InvalidOperation exception because the Queue is empty. I'm not sure what I'm doing wrong shouldn't the signal.WaitOne() above that block the the queue is empty?</p>