title: C# put thread to sleep on dequeue?
body: <p>I'm trying to use <a href="http://msdn.microsoft.com/en-us/library/system.net.webclient(VS.80).aspx" rel="nofollow noreferrer">WebClient</a> to download a bunch of files asynchronously. From my understanding, this is possible, but you need to have one <code>WebClient</code> object for each download. So I figured I'd just throw a bunch of them in a queue at the start of my program, then pop them off one at a time and tell them to download a file. When the file is done downloading, they can get pushed back onto the queue. </p>
  
  <p>Pushing stuff onto my queue shouldn't be too bad, I just have to do something like:</p>
  
  <pre><code>lock(queue) {
      queue.Enqueue(webClient);
  }
  </code></pre>
  
  <p>Right? But what about popping them off? I want my main thread to sleep when the queue is empty (wait until another web client is ready so it can start the next download). I suppose I could use a <code>Semaphore</code> alongside the queue to keep track of how many elements are in the queue, and that would put my thread to sleep when necessary, but it doesn't seem like a very good solution. What happens if I forget to decrement/increment my Semaphore every time I push/pop something on/off my queue and they get out of sync? That would be bad. Isn't there some nice way to have <code>queue.Dequeue()</code> automatically sleep until there is an item to dequeue then proceed?</p>
  
  <p>I'd also welcome solutions that don't involve a queue at all. I just figured a queue would be the easiest way to keep track of which WebClients are ready for use.</p>