惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 司徒正美
博客园 - 【当耐特】
Stack Overflow Blog
Stack Overflow Blog
S
Schneier on Security
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
L
LINUX DO - 热门话题
Spread Privacy
Spread Privacy
雷峰网
雷峰网
博客园 - 叶小钗
L
LangChain Blog
MyScale Blog
MyScale Blog
Security Latest
Security Latest
AWS News Blog
AWS News Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
C
CXSECURITY Database RSS Feed - CXSecurity.com
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Hugging Face - Blog
Hugging Face - Blog
S
Securelist
The Hacker News
The Hacker News
T
Threatpost
Martin Fowler
Martin Fowler
Vercel News
Vercel News
Scott Helme
Scott Helme
S
Security @ Cisco Blogs
B
Blog RSS Feed
Microsoft Azure Blog
Microsoft Azure Blog
The GitHub Blog
The GitHub Blog
L
Lohrmann on Cybersecurity
Google Online Security Blog
Google Online Security Blog
T
Threat Research - Cisco Blogs
The Register - Security
The Register - Security
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
A
About on SuperTechFans
爱范儿
爱范儿
G
Google Developers Blog
B
Blog
C
Check Point Blog
G
GRAHAM CLULEY
T
Troy Hunt's Blog
V
Visual Studio Blog
T
The Blog of Author Tim Ferriss
C
Cisco Blogs
Webroot Blog
Webroot Blog
Blog — PlanetScale
Blog — PlanetScale
TaoSecurity Blog
TaoSecurity Blog
W
WeLiveSecurity
AI
AI
Security Archives - TechRepublic
Security Archives - TechRepublic
T
Tailwind CSS Blog

博客园 - hu晓峰

记winform程序异常排查 记一次wpf 背景图的坑点 【Unity踩坑】Unity项目管理员权限问题(Unity is running as administrator ) 依赖注入 微服务聚合查询 libmodbus编译为64位动态库 一文读懂Modbus协议:工业设备的“普通话“通信指南 Mysql union与union all有什么区别? 理解Systemd服务重启策略:on-failure vs always Redis分布式锁正确的实现方法 字典Dictionary.Add不是把新的元素插入到字典最后面 c# Avalonia 架构开发跨平台应用 ‌索引基数 MySQL InnoDB损坏修复:使用innodb_force_recovery 整数取低字节 C#汉字-区位码相互转化类 avalonia在linux下运行出现Default font family name can't be null or empty问题的解决 ICMP timestamp请求响应漏洞CVE-1999-0524解决方法 详解mysql的for update 使用Redis的SETNX命令实现分布式锁 ASP.NET Core中如何对不同类型的用户进行区别限流
C# 解决串口通讯中,返回数据不完整
hu晓峰 · 2025-02-10 · via 博客园 - hu晓峰
 
博客园 | 首页 | 新随笔 | 联系 | 订阅 订阅 | 管理

从网上搜索,解决这个问题有两个方式:

  解决办法有两种,
  一个是在DataReceived事件里加入
  System.Threading.Thread.Sleep(600); 
  byte[] buffer=new byte[commPlc.BytesToRead];
  这样可以等待缓冲区的数据缓冲好,一次接收数据,也就是只触发一次DataReceived事件

  方法二:
  将instr定义成全局变量,删除事件里的instr="";这样可以保证每次触发的时候不会清空instr

方法一的缺点是代码量大,而且是明明可以等待若干毫秒后,接收缓存区会自动填满。这这时再去取值。就无需自动建立“缓存区”。这个方法属于重复建立缓存区。

方法二的缺点也很明显。由于数据量不同,固定等待时间天然存在bug和浪费时间。

笔者尝试了一种新的方式,克服上面两种方式的缺点。

 这样,不管数据多长,最多浪费20ms

而且从缓冲区取到的数值就是自己需要的数值。

测试结果如下:

  

 

 整个测试下来,读取25个bytes,有些时候只需要等待1次,大多数情况等待2次或3次。即测试成功!

发表于 2025-02-10 09:30  hu晓峰  阅读(486)  评论(0)    收藏  举报