title: What is a good way to shutdown Threads blocked on NamedPipeServer#WaitForConnection?
body: <p>I start my application which spawns a number of Threads, each of which creates a NamedPipeServer (.net 3.5 added managed types for Named Pipe IPC)  and waits for clients to connect (Blocks). The code functions as intended. </p>
  
  <pre><code>private void StartNamedPipeServer()
    {
      using (NamedPipeServerStream pipeStream =
                      new NamedPipeServerStream(m_sPipeName, PipeDirection.InOut, m_iMaxInstancesToCreate, PipeTransmissionMode.Message, PipeOptions.None))
      {
        m_pipeServers.Add(pipeStream);
        while (!m_bShutdownRequested)
        {
          pipeStream.WaitForConnection();
          Console.WriteLine("Client connection received by {0}", Thread.CurrentThread.Name);
          ....  
  </code></pre>
  
  <p>Now I also need a Shutdown method to bring this process down cleanly. I tried the usual bool flag isShutdownRequested trick. But the pipestream stays blocked on the WaitForConnection() call and the thread doesn't die.    </p>
  
  <pre><code>public void Stop()
  {
     m_bShutdownRequested = true;
     for (int i = 0; i &lt; m_iMaxInstancesToCreate; i++)
     {
       Thread t = m_serverThreads[i];
       NamedPipeServerStream pipeStream = m_pipeServers[i];
       if (pipeStream != null)
       {
         if (pipeStream.IsConnected)
            pipeStream.Disconnect();
         pipeStream.Close();
         pipeStream.Dispose();
       }
  
       Console.Write("Shutting down {0} ...", t.Name);
       t.Join();
       Console.WriteLine(" done!");
     }
  } 
  </code></pre>
  
  <p>Join never returns. </p>
  
  <p>An option that I didnt try but would possibly work is to call Thread.Abort and eat up the exception. But it doesn't feel right.. Any suggestions</p>
  
  <p><strong>Update 2009-12-22</strong><br>
  Sorry for not posting this earlier.. This is what I received as a response from Kim Hamilton (BCL team)</p>
  
  <blockquote>
    <p>The "right" way to do an interruptible
    WaitForConnection is to call
    BeginWaitForConnection, handle the new
    connection in the callback, and close
    the pipe stream to stop waiting for
    connections.  If the pipe is closed,
    EndWaitForConnection will throw
    ObjectDisposedException which the
    callback thread can catch, clean up
    any loose ends, and exit cleanly.</p>
    
    <p>We realize this must be a common
    question, so someone on my team is
    planning to blog about this soon.</p>
  </blockquote>