title: What's the proper way to wait on a Semaphore?
body: <p>I thought that the following code would let all the 10 threads run, two at a time, and then print "done" after <code>Release()</code> is called 10 times. But that's not what happened:</p>
  
  <pre><code>        int count = 0;
  
          Semaphore s = new Semaphore(2, 2);
          for (int x = 0; x &lt; 10; x++)
          {
              Thread t = new Thread(new ThreadStart(delegate()
              {
                  s.WaitOne();
                  Thread.Sleep(1000);
                  Interlocked.Increment(ref count);                       
                  s.Release();
              }));
              t.Start(x);
          }
  
          WaitHandle.WaitAll(new WaitHandle[] { s });
          Console.WriteLine("done: {0}", count);
  </code></pre>
  
  <p>output:</p>
  
  <pre><code>done: 6
  </code></pre>
  
  <p>If the only way to implement the functionality I'm looking for is to pass an <code>EventWaitHandle</code> to each thread and then do a <code>WaitAll()</code> on an array of those <code>EventWaitHandles</code>, then what's the meaning of doing a <code>WaitAll()</code> on an array of only a semaphore? In other words, when does the waiting thread unblock?</p>