title: C#: Asynchronous NamedPipeServerStream The pipe is being closed exception
body: <p>My previous question on the same theme: <a href="https://stackoverflow.com/questions/11435262/c-asynchronous-namedpipeserverstream-understanding">C#: Asynchronous NamedPipeServerStream understanding</a>
  Now I have next:</p>
  
  <pre><code>private void StartListeningPipes()
  {
      try
      {
          isPipeWorking = true;
                  namedPipeServerStream = new NamedPipeServerStream(PIPENAME, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, BUFFERSIZE, BUFFERSIZE);
                  Console.Write("Waiting for client connection...");
                  while(isPipeWorking)
                  {
              IAsyncResult asyncResult = namedPipeServerStream.BeginWaitForConnection(this.WaitForConnectionAsyncCallback, null);
                          Thread.Sleep(3*1000);
                  }
          }
          //// Catch the IOException that is raised if the pipe is broken or disconnected.
          catch (IOException e)
          {
          Console.WriteLine("IOException: {0}. Restart pipe server...", e.Message);
                  StopListeningPipes();
                  StartListeningPipes();
          }
          //// Catch ObjectDisposedException if server was stopped. Then do nothing.
          catch (ObjectDisposedException)
          {
          }
  }
  
  private void WaitForConnectionAsyncCallback(IAsyncResult result)
  {
      try
      {
          namedPipeServerStream.EndWaitForConnection(result);
          Console.WriteLine("Client connected.");
          namedPipeServerStream.WaitForPipeDrain();
                  byte[] buff = new byte[BUFFERSIZE];
                  namedPipeServerStream.Read(buff, 0, BUFFERSIZE);
                  string recStr = TrimNulls(buff);
                  Array.Clear(buff, 0, buff.Length);
                  Console.WriteLine();
                  Console.WriteLine("'"+recStr+"'");
      }
      catch (Exception e)
      {
          Console.WriteLine("Error: " + e.Message);            
          }
  }
  </code></pre>
  
  <p>But I'm getting</p>
  
  <p><code>The pipe is being closed Exception</code> everytime I receive a message from client</p>
  
  <p>Why?</p>
  
  <p>My client:</p>
  
  <pre><code> using (NamedPipeClientStream pipeStream = new NamedPipeClientStream(General.PIPENAME))
  {
      try
          {
          byte[] bytes = General.Iso88591Encoding.GetBytes(sendingMessage);
                  pipeStream.Write(bytes, 0, bytes.Length);
                  pipeStream.Flush();
                  pipeStream.WaitForPipeDrain();
          }
          catch (TimeoutException)
          {
          Console.WriteLine("Timeout error!");
          }
      catch (Exception e)
          {
          Console.WriteLine(string.Format("Error! ", e.Message));
          }
  }
  </code></pre>
  
  <hr>
  
  <p>Final code at the moment is:</p>
  
  <pre><code>/// &lt;summary&gt;
          /// Create new NamedPipeServerStream for listening to pipe client connection
          /// &lt;/summary&gt;
          private void ListenForPipeClients()
          {
              if (!this.isListeningToClients)
                  return;
  
              try
              {
                  PipeSecurity ps = new PipeSecurity();
                  PipeAccessRule par = new PipeAccessRule("Everyone", PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);
                  ps.AddAccessRule(par);
                  pipeClientConnection = new NamedPipeServerStream(General.PIPENAME, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, General.BUFFERSIZE, General.BUFFERSIZE, ps);
                  Console.Write("Waiting for client connection...");
                  /*namedPipeServerStream.WaitForConnection();
                  OnPipeConnected(namedPipeServerStream);*/
                  IAsyncResult result = pipeClientConnection.BeginWaitForConnection(OnPipeConnected, pipeClientConnection);
              }
              catch (ObjectDisposedException)
              {
                  //// Catch ObjectDisposedException if server was stopped. Then do nothing.
              }
              catch (Exception e)
              {
                  Console.WriteLine("Error occures: {0}. Restart pipe server...", e.Message);
                  this.logger.Add(LogLevel.Warning, string.Format("Error occures: {0}. Restart pipe server...", e.Message));
                  ListenForPipeClients();
              }
          }
  
          /// &lt;summary&gt;
          /// Async callback on client connected action
          /// &lt;/summary&gt;
          /// &lt;param name="asyncResult"&gt;Async result&lt;/param&gt;
          private void OnPipeConnected(IAsyncResult asyncResult)
          {
              using (var conn = (NamedPipeServerStream)asyncResult.AsyncState)
              {
                  try
                  {
                      conn.EndWaitForConnection(asyncResult);
                      Console.WriteLine("Client connected.");
                      PipeClientConnection clientConnection = new PipeClientConnection(conn, notifierSenderCache, defaultStorageTime);
                  }
                  catch (Exception e)
                  {
                      Console.WriteLine(e.Message);
                      this.logger.Add(LogLevel.Warning, e.Message);
                  }
              }
  
              ListenForPipeClients();
          }
  </code></pre>