清除C#中的串口接收缓冲区

man*_*c84 13 c# serial-port

只是想知道我们如何在C#中清除串口的接收缓冲区.似乎接收缓冲区中的数据只是不断累积.例如,输入数据流是:[数据A],[数据B],[数据C].我想要的数据只是[数据C].我想这样做,当我收到[数据A]和[数据B]时,我会做一个明确的缓冲区.只有收到[数据C]时,我才会继续处理.这是用C#做的吗?

Sim*_*mon 14

如果你正在使用System.IO.Ports.SerialPort那么你可以使用这两种方法:

DiscardInBuffer()DiscardOutBuffer()冲洗缓冲区.

如果要从串行端口读取数据:

private void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    if (!this.Open) return; // We can't receive data if the port has already been closed.  This prevents IO Errors from being half way through receiving data when the port is closed.
    string line = String.empty;
    try
    {
        line = _SerialPort.ReadLine();
        line = line.Trim();
       //process your data if it is "DATA C", otherwise ignore
    }
    catch (IOException ex)
    {
        //process any errors
    }
}
Run Code Online (Sandbox Code Playgroud)


Cde*_*eez 10

使用port.DiscardOutBuffer(); and port.DiscardInBuffer();清除串行端口的缓冲区


car*_*ras 5

你可以使用像

port.DiscardOutBuffer();
port.DiscardInBuffer();
port.Close();
port.DataReceived -= new SerialDataReceivedEventHandler(onDataReceived);
port = null;
Run Code Online (Sandbox Code Playgroud)


小智 5

有两个缓冲区。一个缓冲区与串行端口相关联,另一个与其基本流相关联,来自端口缓冲区的数据流入其中。DiscardIn Buffer() 只是从丢弃的串行端口缓冲区中获取数据。您将读取的基本流中仍有数据。所以,除了使用 DiscardInBuffer,还要使用 SP.BaseStream.Flush()。现在你有一个干净的石板!如果您没有获得大量数据,只需删除基本流:SP.BaseStream.Dispose()。

由于您仍在获取数据接收事件,您可以阅读它,而不会让自己处于丢失数据的危险之中。