简体   繁体   English

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

[英]Clear serial port receive buffer in C#

Just want to know how do we clear the receive buffer of my serial port in C#. 只想知道我们如何清除C#中我的串行端口的接收缓冲区。 Seems like the data in the receive buffer just keep accumulating. 好像接收缓冲区中的数据不断累积。 For example, the flow of incoming data is: [Data A], [Data B], [Data C]. 例如,传入数据的流为:[数据A],[数据B],[数据C]。 The data I want is just [Data C]. 我想要的数据只是[数据C]。 I'm thinking of doing like, when I receive [Data A] and [Data B], I do a clear buffer. 我正在考虑这样做,当我收到[数据A]和[数据B]时,我做了一个明确的缓冲区。 Only when [Data C] is received, I continue process. 仅当接收到[Data C]时,我才继续处理。 Is this the way to do it in C#? 这是用C#做到的方式吗?

If you are using the System.IO.Ports.SerialPort then you could use the two methods: 如果使用的是System.IO.Ports.SerialPort则可以使用两种方法:

DiscardInBuffer() and DiscardOutBuffer() to flush the buffers. DiscardInBuffer()DiscardOutBuffer()刷新缓冲区。

If you are reading the data from a serial port: 如果要从串行端口读取数据:

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
    }
}

Use port.DiscardOutBuffer(); and port.DiscardInBuffer(); 使用port.DiscardOutBuffer(); and port.DiscardInBuffer(); port.DiscardOutBuffer(); and port.DiscardInBuffer(); to clear the serial port buffers 清除串行端口缓冲区

you can use like 你可以用像

port.DiscardOutBuffer();
port.DiscardInBuffer();
port.Close();
port.DataReceived -= new SerialDataReceivedEventHandler(onDataReceived);
port = null;

There are two buffers. 有两个缓冲区。 One buffer is associated with the serial port and the other with its base stream, where data from the port buffer is streamed into. 一个缓冲区与串行端口关联,另一个缓冲区与它的基本流关联,来自端口缓冲区的数据将流入该基本流。 DiscardIn Buffer() just gets data from the Serial Port buffer discarded. DiscardIn Buffer()只是从丢弃的串行端口缓冲区中获取数据。 There is still data in the Base Stream that you will read. 基本流中仍然有您将要读取的数据。 So, besides using DiscardInBuffer, also use SP.BaseStream.Flush(). 因此,除了使用DiscardInBuffer之外,还请使用SP.BaseStream.Flush()。 Now you have a clean slate! 现在,您有了一个干净的状态! If you are not getting a lot of data, simply get rid of the base stream: SP.BaseStream.Dispose(). 如果您没有得到很多数据,只需除去基本流:SP.BaseStream.Dispose()。

Since you are still getting the data received event, yo can read it and not put yourself in jeopardy of losing data. 由于您仍在获取数据接收事件,因此您可以读取它,而不会陷入丢失数据的危险中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM