private void PerformReadOnCom1FromCom2(SerialPort com1, SerialPort com2, char[] expectedChars, char[] rcvBuffer, int offset, int count) { char[] buffer = new char[expectedChars.Length]; char[] oldRcvBuffer = (char[])rcvBuffer.Clone(); int numBytesWritten = com1.Encoding.GetByteCount(expectedChars); int totalBytesRead = 0; int totalCharsRead = 0; while (true) { int charsRead; try { charsRead = com1.Read(rcvBuffer, offset, count); } catch (TimeoutException) { break; } // While there are more characters to be read int bytesRead = com1.Encoding.GetByteCount(rcvBuffer, offset, charsRead); totalBytesRead += bytesRead; if (expectedChars.Length < totalCharsRead + charsRead) { //If we have read in more characters than we expect //1<DEBUG> Debug.WriteLine("count={0}, charsRead={1} expectedChars.Length={2}, totalCharsRead={3}", count, charsRead, expectedChars.Length, totalCharsRead); Debug.WriteLine("rcvBuffer"); TCSupport.PrintChars(rcvBuffer); Debug.WriteLine("\nexpectedChars"); TCSupport.PrintChars(expectedChars); //1</DEBUG> Fail("ERROR!!!: We have received more characters then were sent"); } if (count != charsRead && (count < charsRead || ((expectedChars.Length - totalCharsRead) != charsRead && !TCSupport.IsSurrogate(expectedChars[totalCharsRead + charsRead])))) { //If we have not read all of the characters that we should have //1<DEBUG> Debug.WriteLine("count={0}, charsRead={1} expectedChars.Length={2}, totalCharsRead={3}", count, charsRead, expectedChars.Length, totalCharsRead); Debug.WriteLine("rcvBuffer"); TCSupport.PrintChars(rcvBuffer); Debug.WriteLine("\nexpectedChars"); TCSupport.PrintChars(expectedChars); //1</DEBUG> Fail("ERROR!!!: Read did not return all of the characters that were in SerialPort buffer"); } VerifyBuffer(rcvBuffer, oldRcvBuffer, offset, charsRead); Array.Copy(rcvBuffer, offset, buffer, totalCharsRead, charsRead); totalCharsRead += charsRead; Assert.Equal(numBytesWritten - totalBytesRead, com1.BytesToRead); oldRcvBuffer = (char[])rcvBuffer.Clone(); } VerifyBuffer(rcvBuffer, oldRcvBuffer, 0, rcvBuffer.Length); //Compare the chars that were written with the ones we expected to read for (int i = 0; i < expectedChars.Length; i++) { if (expectedChars[i] != buffer[i]) { Fail("ERROR!!!: Expected to read {0} actual read {1} at {2}", (int)expectedChars[i], (int)buffer[i], i); } } Assert.Equal(0, com1.BytesToRead); }