title: Multi-threading with .Net HttpListener
body: <p>I have a listener:</p>
  
  <pre><code>listener = new HttpListener();
  listener.Prefixes.Add(@"http://+:8077/");
  listener.Start();
  listenerThread = new Thread(HandleRequests);
  listenerThread.Start();
  </code></pre>
  
  <p>And I am handling requests:</p>
  
  <pre><code>private void HandleRequests()
  {
      while (listener.IsListening)
      {
          var context = listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener);
          context.AsyncWaitHandle.WaitOne();
      }
  }
  
  private void ListenerCallback(IAsyncResult ar)
  {
      var listener = ar.AsyncState as HttpListener;
  
      var context = listener.EndGetContext(ar);
  
      //do some stuff
  }
  </code></pre>
  
  <p>I would like to write <code>void Stop()</code> in such a way, that:</p>
  
  <ol>
  <li>It will block until all currently handled requests will end (ie. will wait for all threads to "do some stuff").</li>
  <li>While it will wait for already started requests, it will not allow any more requests (ie. return at the beginning of <code>ListenerCallback</code>).</li>
  <li>After that it will call <code>listener.Stop()</code> (<code>listener.IsListening</code> became false).</li>
  </ol>
  
  <p>How could it be write?</p>
  
  <p><strong>EDIT</strong>: What do you think about this solution? Is it safe?</p>
  
  <pre><code>public void Stop() 
  {
      lock (this)
      {
          isStopping = true;
      }
      resetEvent.WaitOne(); //initially set to true
      listener.Stop();
  }
  
  private void ListenerCallback(IAsyncResult ar)
  {
      lock (this)
      {
          if (isStopping)
              return;
  
          resetEvent.Reset();
          numberOfRequests++;
      }
  
      var listener = ar.AsyncState as HttpListener;
  
      var context = listener.EndGetContext(ar);
  
      //do some stuff
  
      lock (this)
      {
          if (--numberOfRequests == 0)
              resetEvent.Set();
      }
  }
  </code></pre>