快速读取和解析连续数据的方法

编程入门 行业动态 更新时间:2024-10-23 09:31:46
本文介绍了快速读取和解析连续数据的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个线程可以读取和解析串行数据.消息采用二进制格式,并以字符"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.

更多推荐

快速读取和解析连续数据的方法

本文发布于:2023-11-11 06:17:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1577607.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:快速   方法   数据

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!