问题描述
我有一个线程可以读取和解析串行数据.消息采用二进制格式,并以字符"F","S","Q"或"M"开头.没有换行符,也没有特殊的结尾字符(上面的字符表示消息已完成,并且可以解析消息之前的所有内容).
I've got a thread to read and parse serial data.The messages are in binary format and start with either the character 'F', 'S', 'Q' or 'M'.There are no newlines and there is no special ending character (the characters above state that a message is finished and everything before it is ready to be parsed).
我如何连续读取和解析数据?
How do I continuously read and parse the data?
我想到的就是拥有一个4096字节长的输入缓冲区(字节数组),然后执行以下步骤:
All that comes to my mind is having a 4096 byte long input buffer (byte array) and then follow this procedure:
- 手动跟踪缓冲区中的位置
- 通过
SerialPort.Read(缓冲区,位置,byteCount)
向其添加可用数据 - 尝试从缓冲区解析尽可能多的消息
- 将其余部分复制到临时缓冲区
- 重置输入缓冲区
- 将临时缓冲区的内容复制到原始缓冲区
- 设置缓冲区中的位置
您能想到更快/更简便的方法吗?
推荐答案
一种非常简单的成功方法是停止尝试使其更快.毫无疑问,串行端口数据速率非常非常低,而现代计算机却非常非常快.您的 Read()
调用仅返回一个字节,很少返回2.
A very simple way to get ahead is to stop trying to make it faster. There is no point, serial port data rates are very, very low and modern computers are very, very fast. Your Read()
call only ever returns a single byte, rarely 2.
请注意,这很难看到,当您调试并单步执行代码时,您会人为地减慢程序速度.允许接收更多字节,并因此通过 Read()
调用返回更多字节.但是,当程序以正常速度运行时,不会发生这种情况.
Note that this is hard to see, when you debug and single-step through the code then you'll artificially slow down your program a great deal. Allowing more bytes to be received and thus more of them getting returned by the Read()
call. But this doesn't happen when the program runs at normal speed.
因此,请改用 SerialPort.BaseStream.ReadByte()
.使代码非常简单.
So use SerialPort.BaseStream.ReadByte()
instead. Makes the code very simple.
这篇关于快速读取和解析连续数据的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!