title: Background worker synchronization
body: <p>Lets say I have a class that is supposed to generate some ID (for example GUID) for me. Now unfortunately the ID generation is a somewhat long process and if I need a hundred of those I run into a problem of significant slowdowns. In order to avoid those, I keep a queue of pre-generated ID, and when this queue starts to run down on them I use the BackgroundWorker to generate new ones and place them in the queue. But there are some problems I've run into. The biggest one at the moment is how to make sure that in case the queue compleatelly runs out on IDs the main thread waits for the BackroundWorker to generate and place them in the queue. Heres the code that I have at the moment.</p>
  
  <pre><code>public class IdGenerator
  {
      private Queue&lt;string&gt; mIds = new Queue&lt;string&gt;();
      private BackgroundWorker mWorker = new BackgroundWorker();
      private static EventWaitHandle mWaitHandle = new AutoResetEvent(false);
  
      public IdGenerator()
      {
          GenerateIds();
  
          this.mWorker.DoWork += new DoWorkEventHandler(FillQueueWithIds);
      }
  
      private void GenerateIds()
      {
          List&lt;string&gt; ids = new List&lt;string&gt;();
  
          for (int i = 0; i &lt; 100; i++ )
          {
              ids.Add(Guid.NewGuid().ToString());
          }
  
          lock (this.mIds)
          {
  
              foreach (string id in ids)
              {
                  this.mIds.Enqueue(id);
              } 
          }            
      }
  
      public string GetId()
      {
          string id = string.Empty;
  
          lock (this.mIds)
          {
              if (this.mIds.Count &gt; 0)
              {
                  id = this.mIds.Dequeue();
              }
  
              if (this.mIds.Count &lt; 100)
              {
                  if (!this.mWorker.IsBusy)
                  {
                      this.mWorker.RunWorkerAsync();
                  }
              }
          }
  
          if (this.mIds.Count &lt; 1)
          {
              mWaitHandle.WaitOne();
          }
  
          return id;
      }
  
      void FillQueueWithIds(object sender, DoWorkEventArgs e)
      {
          GenerateIds();
          mWaitHandle.Set();   
      }
  }
  </code></pre>
  
  <p>Obviously it doesn't work correctly. It seems that I have a problem with proper timing for calling WaitOne and Set methods. And sometimes the IsBusy property returns true even though the worker has already completed his work.</p>
  
  <hr>
  
  <p>EDIT:</p>
  
  <p>Its a WinForm and I'm required to use .NET 2.0</p>