title: How to use named pipes in C# correctly -- several connections, server recreation etc
body: <p>I need to implement an inter-process communication between C# applications. I decided to use named pipes and wrote the following code:</p>
  
  <p><strong>Server</strong></p>
  
  <pre><code>while (true)
  {
      using (var server = new NamedPipeServerStream("some_pipe"))
      {
          server.WaitForConnection();
          using (var reader = new StreamReader(server))
          {
              string line = reader.ReadLine();
              MessageBox.Show(line);
          }
      }
  }
  </code></pre>
  
  <p><strong>Client</strong></p>
  
  <pre><code>using (var client = new NamedPipeClientStream("some_pipe"))
  {
      client.Connect();
  
      using (var writer = new StreamWriter(client))
      {
          writer.AutoFlush = true;
          writer.WriteLine(path);
          client.WaitForPipeDrain();
      }
  }
  </code></pre>
  
  <p>I have the following questions about it:</p>
  
  <ul>
  <li>Is this solution correct at all? Is there any issues or bugs you already see?</li>
  <li>What will happen if the second client will try to connect to this server? Will it wait for the first client to finish or just send its message along with another client's instance resulting in garbage?</li>
  <li>Should I really create another instance of <code>NamedPipeServerStream</code> class every time? If I move its construction from the <code>while (true)</code> loop it gives me an exception "Cannot access a closed pipe". How can I avoid it? If I can't avoid it and should re-create this object every time, what will happen if there is no <code>NamedPipeServerStream</code> at the moment when client will try to connect to it?</li>
  </ul>