title: C# async named pipes wait for ever
body: <p>I am using asynchronous pipes and at some point both the server and the client wait for each other and do nothing. Here is my code:</p>
  
  <h1>Server:</h1>
  
  <pre><code>var buffer = new byte[BufferSize];
  using (var server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
  {
      // Wait for client.
      Logger.Trace("Waiting for connection ...");
      var asyncResult = server.BeginWaitForConnection(a =&gt; { }, null);
       while (true)
       {
            await Task.Delay(MillisecondsDelay);
            if (asyncResult.IsCompleted) break;
        }
        server.EndWaitForConnection(asyncResult);
        Logger.Trace("Connection established.");
  
  
         using (var sr = new StreamReader(server))
         using (var sw = new StreamWriter(server))
         {
               // Send work.
               Logger.Trace("Sending operations...");
               await sw.WriteAsync(JsonConvert.SerializeObject(data));
               await sw.FlushAsync();
               server.WaitForPipeDrain();
  
                // Wait for response.
                var bytesRead = await server.ReadAsync(buffer, 0, buffer.Length);
  
         .....
  </code></pre>
  
  <h1>Client:</h1>
  
  <pre><code>        // Read data from the pipe...
   using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous))
   {
        Logger.Trace("Connecting to server...");
        client.Connect();
        Logger.Trace("Connected.");
  
        using (var sr = new StreamReader(client))
        using (var sw = new StreamWriter(client))
        {
             // Read operations.
             Logger.Trace("Waiting operations...");
             var text = await sr.ReadToEndAsync();
         .....
  </code></pre>
  
  <p>The logs that I take are these:</p>
  
  <pre><code>2016-10-04 16:09:51.5375 =&gt; (TRACE) | MyController.Execute : Waiting for connection ... |  
  2016-10-04 16:09:52.0706 =&gt; (TRACE) | MyController+&lt;Execute&gt;d__5.MoveNext : Connection established. |  
  2016-10-04 16:09:52.0706 =&gt; (TRACE) | MyController+&lt;Execute&gt;d__5.MoveNext : Sending operations... |  
  </code></pre>
  
  <p>and :</p>
  
  <pre><code>2016-10-04 16:09:51.8486 =&gt; (TRACE) | EXE.Program.Process : Connecting to server... | 
  2016-10-04 16:09:51.8696 =&gt; (TRACE) | EXE.Program.Process : Connected. | 
  2016-10-04 16:09:51.8696 =&gt; (TRACE) | EXE.Program.Process : Waiting operations... | 
  </code></pre>
  
  <p>And then nothing!</p>
  
  <p>After that it seems like deadlocked.</p>
  
  <p>I think I should use <code>WaitForPipeDrain()</code> after each write by the server or the client and I do that, but it doesn't seem to help.</p>
  
  <p>The client read operation never returns.</p>
  
  <p>Any ideas anyone?</p>