title: C# Named Pipes in message mode sometimes merge messages?
body: <p>I'm using Named Pipes in a project I'm working on, both sides are written in C# (client and server) and both are on the same computer (The named pipes are used for RPC). The named pipes on both sides are set to use 'PipeTransmissionMode.Message' mode which according to my understanding should "pack" each chunk of data passed to pipe.Write() in a single message and pipe.Read() on the other end should receive the entire message or none of it.</p>
  
  <p>While trying to deserialize the data on the receiving end, I saw that I get big chucks of data, bigger than the packets I sent. So I made a small test, I created two Applications, server and client, which looks like this:</p>
  
  <p>Server:</p>
  
  <pre><code>class Program
  {
      static void Main(string[] args)
      {
          NamedPipeServerStream pipe = new NamedPipeServerStream("TestPipe", PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 1024, 1024);
          pipe.WaitForConnection();
  
          Random random = new Random();
  
          while(true)
          {
              byte[] buffer = new byte[32];
              random.NextBytes(buffer);
              pipe.Write(buffer, 0, buffer.Length);
              Console.WriteLine(buffer.Length);
          }
      }
  }
  </code></pre>
  
  <p>Client:</p>
  
  <pre><code>class Program
  {
      static void Main(string[] args)
      {
          NamedPipeClientStream pipe = new NamedPipeClientStream(".", "TestPipe", PipeDirection.InOut, PipeOptions.Asynchronous);
          pipe.Connect();
  
          while(true)
          {
              byte[] buffer = new byte[2048];
              int read = pipe.Read(buffer, 0, buffer.Length);
              Console.WriteLine(read);
  
              if(read &gt; 32)
                 Console.WriteLine("Big");
          }
      }
  }
  </code></pre>
  
  <p>Running this, the server outputs only 32 (which is what I expected) but the client, sometimes output 64 followed by "Big". What's going on?</p>
  
  <p>P.S: If I put <code>Thread.Sleep(100)</code> on the server loop, it works as expected (writes only 32 on both sides)</p>
  
  <p>EDIT:
  If I put a <code>Thread.Sleep(100)</code> on the server and <code>Thread.Sleep(200)</code> on the client, I receive bigger packets more often, which leads me to believe that if more than one message is arrived before the call to read then read returns all of them. How can I ensure each read will return only one message?</p>