title: How to read all the bytes from Serialport as indicated by BytesToRead
body: <p>I am trying to read data off a meter. The holy grail is <code>1000 samples per second</code> which the device actually supports. Baud rate is <code>38400, Parity.None</code> and <code>Stopbits.One</code> if that matters. I am using the <code>binary mode</code> to keep things as swift as possible. I plan using the DataReceived event as below.</p>
  
  <pre><code>private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
      {
          int bytesToRead = _serialPort.BytesToRead;
          byte[] data = new byte[bytesToRead];
          int actualBytesRead = 0;
          do
          {
              actualBytesRead = serialPort.Read(data, 0, bytesToRead);
          } while (actualBytesRead != bytesToRead);
  
          //At this point assume that the data byte array has all the data
      }
  </code></pre>
  
  <p><strong>It seems that <code>BytesToRead</code> will return all the bytes which are available to read for that event.</strong> However as the <a href="https://msdn.microsoft.com/en-us/library/ms143549(v=vs.110).aspx" rel="nofollow noreferrer">link</a> says </p>
  
  <pre><code>The SerialPort class buffers data, but the stream object contained in the
  SerialPort.BaseStream property does not. Therefore, the SerialPort object
  and the stream object might differ on the number of bytes that are 
  available to read. When bytes are buffered to the SerialPort object, the 
  BytesToRead property includes these bytes in its value; 
  however, these bytes might not be accessible to the stream contained in
  the BaseStream property. 
  </code></pre>
  
  <p><strong>And <code>Read</code> returns only the number of bytes it has read.</strong>
  So as a precaution against this I plan to read continually till I get the number of bytes read same as what BytesToRead indicated for the event raised. However there are few points I am not clear on.</p>
  
  <ul>
  <li>Will this even work. I am not sure if the data once read off the buffer of a serial port will remain to exist. </li>
  <li>If not then while looping around should I keep the number of bytes to read equal to BytesToRead or should I adjust it for the number of bytes already read from the buffer.</li>
  <li>I am pretty much hitting the buffer constantly till I get all the bytes. Is this right? Will this lead to locking issues in the sense that bytes will take longer to become available? </li>
  <li>Is there any better way to get all the bytes as indicated by BytesToRead?</li>
  </ul>