如何正确使用 SerialPort.DiscardInBuffer? [英] How to correctly use SerialPort.DiscardInBuffer?

查看:41
本文介绍了如何正确使用 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆