在C#中使用串口接收数据时发现,在完整的接收完一次数据后,还会再次进入串口接收事件。
在网上搜索资料发现其他开发者也有遇到该问题:
[1] c#串口事件接受一次数据莫名其妙会触发两次 原文链接:https://www.52pojie.cn/thread-1009851-1-1.html
[2]Serial Port object's DataReceived Event firing twice 原文链接:https://stackoverflow.com/questions/30296199/serial-port-objects-datareceived-event-firing-twice
其中[2]提到:串口接收事件触发2次是正常的,第1次是有数据接收,第2次收到的是EOF标志,直接忽略掉第2次就好了。
在串口接收事件开头加入该部分判断后如下:
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
//接收到EOF则直接退出
if (e.EventType == System.IO.Ports.SerialData.Eof)
{
return;
}
...
}
在串口接收事件的if语句处设置断点进行调试,第一次进入时:e.EventType 为System.IO.Po