title: Why doesn't my NamedPipeServerStream wait?
body: <p>I'm working with a NamedPipeServerStream to communicate between two processes.  Here is the code where I initialize and connect the pipe:</p>
  
  <pre><code>void Foo(IHasData objectProvider)
  {
      Stream stream = objectProvider.GetData();
      if (stream.Length &gt; 0)
      {
          using (NamedPipeServerStream pipeServer = new NamedPipeServerStream("VisualizerPipe", PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
          {
              string currentDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
              string uiFileName = Path.Combine(currentDirectory, "VisualizerUIApplication.exe");
              Process.Start(uiFileName);
              if(pipeServer.BeginWaitForConnection(PipeConnected, this).AsyncWaitHandle.WaitOne(5000))
              {
                  while (stream.CanRead)
                  {
                      pipeServer.WriteByte((byte)stream.ReadByte());
                  }
              }
              else
              {
                  throw new TimeoutException("Pipe connection to UI process timed out.");
              }
          }
      }
  }
  
  private void PipeConnected(IAsyncResult e)
  {
  }
  </code></pre>
  
  <p>But it never seems to wait.  I constantly get the following exception:</p>
  
  <p><strong>System.InvalidOperationException: Pipe hasn't been connected yet.
     at System.IO.Pipes.PipeStream.CheckWriteOperations()
     at System.IO.Pipes.PipeStream.WriteByte(Byte value)
     at PeachesObjectVisualizer.Visualizer.Show(IDialogVisualizerService windowService, IVisualizerObjectProvider objectProvider)</strong></p>
  
  <p>I would think that after the wait returns everything should be ready to go.  </p>
  
  <p>If I use pipeServer.WaitForConnection() everything works fine, but hanging the application if the pipe doesn't connect is not an option.</p>