我正在尝试使用ReadAll
来实现SerialPort
方法,这将确保它读取尽可能多的字节(我希望使用此函数从串行端口读取)。这种实现方式是否正确?
public static void ReadWholeArray (SerialPort sp, byte[] data)
{
int offset=0;
int remaining = data.Length; // ensure we read this many bytes
while (remaining > 0)
{
int read = sp.Read(data, offset, remaining);
if (read <= 0)
throw new EndOfStreamException
(String.Format("End of data reached with {0} bytes left to read", remaining));
remaining -= read;
offset += read;
}
}
PS。类似的WriteAll
方法是否有必要? (或写入是否确保写入被告知的字节数?)。