清除C#中的串口接收缓冲区
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11571522/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Clear serial port receive buffer in C#
提问by maniac84
Just want to know how do we clear the receive buffer of my serial port in 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]. The data I want is just [Data C]. I'm thinking of doing like, when I receive [Data A] and [Data B], I do a clear buffer. Only when [Data C] is received, I continue process. Is this the way to do it in C#?
只是想知道我们如何在C#中清除我的串口的接收缓冲区。似乎接收缓冲区中的数据只是不断累积。例如传入数据的流向为:[Data A]、[Data B]、[Data C]。我想要的数据只是 [Data C]。我正在考虑这样做,当我收到 [Data A] 和 [Data B] 时,我会清除缓冲区。只有当收到 [Data C] 时,我才继续处理。这是在 C# 中实现的方法吗?
采纳答案by Simon
If you are using the System.IO.Ports.SerialPortthen 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
}
}
回答by Cdeez
Use port.DiscardOutBuffer(); and port.DiscardInBuffer();to clear the serial port buffers
使用port.DiscardOutBuffer(); and port.DiscardInBuffer();清除串行端口的缓冲区
回答by caras
you can use like
你可以使用像
port.DiscardOutBuffer();
port.DiscardInBuffer();
port.Close();
port.DataReceived -= new SerialDataReceivedEventHandler(onDataReceived);
port = null;
回答by Rajesh Maheshwari
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. There is still data in the Base Stream that you will read. So, besides using DiscardInBuffer, also use 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().
有两个缓冲区。一个缓冲区与串行端口相关联,另一个与其基本流相关联,来自端口缓冲区的数据流入其中。DiscardIn Buffer() 只是从丢弃的串行端口缓冲区中获取数据。您将读取的基本流中仍有数据。所以,除了使用 DiscardInBuffer,还要使用 SP.BaseStream.Flush()。现在你有一个干净的石板!如果您没有获得大量数据,只需删除基本流: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.
由于您仍在获取数据接收事件,您可以阅读它,而不会让自己处于丢失数据的危险之中。

