title: How to implement a continuous producer-consumer pattern inside a Windows Service
body: <p>Here's what I'm trying to do: </p>
  
  <ul>
  <li>Keep a queue in memory of items that need processed (i.e. <code>IsProcessed = 0</code>)</li>
  <li>Every 5 seconds, get unprocessed items from the db, and if they're not already in the queue, add them</li>
  <li>Continuous pull items from the queue, process them, and each time an item is processed, update it in the db (<code>IsProcessed = 1</code>)</li>
  <li>Do this all "as parallel as possible"</li>
  </ul>
  
  <p>I have a constructor for my service like </p>
  
  <pre><code>public MyService()
  {
      Ticker.Elapsed += FillQueue;
  }
  </code></pre>
  
  <p>and I start that timer when the service starts like </p>
  
  <pre><code>protected override void OnStart(string[] args)
  {
      Ticker.Enabled = true;
      Task.Run(() =&gt; { ConsumeWork(); });
  }
  </code></pre>
  
  <p>and my <code>FillQueue</code> is like</p>
  
  <pre><code>private static async void FillQueue(object source, ElapsedEventArgs e)   
  {
      var items = GetUnprocessedItemsFromDb();
      foreach(var item in items)
      {
          if(!Work.Contains(item))
          {
              Work.Enqueue(item);
          }   
      }
  }
  </code></pre>
  
  <p>and my <code>ConsumeWork</code> is like </p>
  
  <pre><code>private static void ConsumeWork()
  {
      while(true)
      {
          if(Work.Count &gt; 0)
          {
              var item = Work.Peek();
              Process(item);
              Work.Dequeue();
          }
          else
          {
              Thread.Sleep(500);
          }
      }
  }
  </code></pre>
  
  <p>However this is probably a naive implementation and I'm wondering whether .NET has any type of class that is exactly what I need for this type of situation.</p>