我想了解如何在C#中清空串口接收缓冲区。看起来接收缓冲区中的数据一直在累积。 例如,接收到的数据流为:[数据A]、[数据B]、[数据C]。而我需要的仅是[数据C]。 我考虑的方法是,在接收到[数据A]和[数据B]时,清空缓冲区。只有当接收到[数据C]时,才继续处理。这是在C#中实现的方法吗?
我想了解如何在C#中清空串口接收缓冲区。看起来接收缓冲区中的数据一直在累积。 例如,接收到的数据流为:[数据A]、[数据B]、[数据C]。而我需要的仅是[数据C]。 我考虑的方法是,在接收到[数据A]和[数据B]时,清空缓冲区。只有当接收到[数据C]时,才继续处理。这是在C#中实现的方法吗?
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
}
}
使用port.DiscardOutBuffer(); 和 port.DiscardInBuffer();
清除串口缓冲区。
port.DiscardOutBuffer();
port.DiscardInBuffer();
port.Close();
port.DataReceived -= new SerialDataReceivedEventHandler(onDataReceived);
port = null;
System.IO.Ports.SerialPort
吗? - Dai