CSharp - Serial Handling Notes
Revision as of 08:35, 26 November 2012 by PeterHarding (talk | contribs) (Created page with " * http://stackoverflow.com/questions/4661486/not-reading-complete-serial-port-data-in-c-sharp?rq=1 Use the data received event to fill a buffer: <pre> private void data...")
Use the data received event to fill a buffer:
private void dataReceived(object sender, SerialDataReceivedEventArgs e) { while (port.BytesToRead > 0){ byte[] newBytes = new byte[port.BytesToRead]; int LengthRead = port.Read(newBytes, 0, newBytes.Length); Array.Resize(ref newBytes, LengthRead); System.Buffer.BlockCopy(newBytes, 0, buffer, positionInBuffer, newBytes.Length); positionInBuffer += newBytes.Length; } }
Looping for an expected number of bytes, in this case causing the TimeoutException:
while (port.BytesToRead < expectedSize) { System.Threading.Thread.Sleep(10); waitingLoop++; if (waitingLoop > TimeOut) // wait for a 1s timeout throw new TimeoutException(); } newBytes = new byte[expectedSize]; LengthRead = port.Read(newBytes, 0, newBytes.Length); if (LengthRead != newBytes.Length) throw new TimeoutException(); // or any exception, doesn't matter...