How to correctly use SerialPort.DiscardInBuffer?(如何正确使用 SerialPort.DiscardInBuffer?)
问题描述
我编写了一个应用程序,它以非常快的速度从串行设备中读取数据.然而,串行端口对象在连续运行约 20 分钟后未能触发 DataReceieved
事件.以编程方式断开和重新连接串行允许事件再次工作,但仅再持续 20 分钟.
I've written an application which reads from a serial device at a very fast rate. The serial port object however, fails to fire the DataReceieved
event after about 20 min of continuous operation. Disconnecting and reconnecting the serial programmatically allows the event to work again but for only another 20 min.
我尝试在每个 DataReceived
事件之后使用 DiscardInBuffer
,这似乎已经解决了问题.但是这种方法会消耗大量的 cpu 时间,并且会降低应用程序的性能.MSDN 提到丢弃串行驱动程序接收缓冲区中的数据"方法,但没有建议何时使用.
I tried using DiscardInBuffer
after every DataReceived
event and this has appeared to have solved the problem. But the method consumes a lot of cpu time and is degrading the performance of the application. MSDN mentions that the method "Discards data from the serial driver's receive buffer.", but fails to suggest when it should be used.
应该何时以及如何使用 DiscardInBuffer
,我是否在针对特定问题的正确上下文中使用它?
When and how should DiscardInBuffer
be used, and am I using it in the correct context for my particular problem ?
执行ErrorReceived
事件后,返回的事件数据表明事件类型为RXOver".
After implementing the ErrorReceived
event, the event data returned indicated the event type was an "RXOver".
推荐答案
经过更多调查,我的问题似乎是一个更根本的问题.由于数据以极快的速度涌入,因此需要连续清除或处理 SerialPort 缓冲区以防止RXOver"错误.我通过在 DataReceived
事件期间读入另一个缓冲区并在另一个单独的线程中处理它来实现这一点.
After more investigations, it appears my problem was more a fundamental issue. Since the data was flooding in at a hot pace, the SerialPort buffer needed to be cleared or processed continuously to prevent the "RXOver" error. I achieved this by reading into another buffer during the DataReceived
event and processed it in another separate thread.
据我了解,DiscardInBuffer
只能选择性地用于清除端口内容以进行初始化,例如在打开端口之前.清除驱动程序缓冲区的过程确实需要一些时间才能完成,因此应该在面向性能的应用程序中明智地使用.
From my understanding the DiscardInBuffer
should only be used selectively to clear the contents of the ports for initialisation purposes, such as before opening a port. The process of clearing the driver buffer does take some time to complete and therefore should be used wisely in a performance orientated application.
这篇关于如何正确使用 SerialPort.DiscardInBuffer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何正确使用 SerialPort.DiscardInBuffer?


- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- MoreLinq maxBy vs LINQ max + where 2022-01-01