使用SerialPort实现ReadAll方法

时间:2015-09-29 07:33:46

标签: c# serial-port

我正在尝试使用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方法是否有必要? (或写入是否确保写入被告知的字节数?)。

0 个答案:

没有答案