是什么导致 .NET SerialPort 类 DataReceived 事件触发? [英] what causes the .NET SerialPort class DataReceived event to fire?

查看:27
本文介绍了是什么导致 .NET SerialPort 类 DataReceived 事件触发?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从 MSDN 文档中了解到,事件 DataReceived 不一定会在每个字节中触发一次.

I understand from the MSDN docs that the event DataReceived will not necessarily fire once per byte.

但是有谁知道导致事件触发的确切机制是什么?

But does anyone know what exactly is the mechanism that causes the event to fire?

每个字节的接收是否会重新启动一个计时器,该计时器必须在事件触发之前达到(例如字节之间的 10 毫秒)?

Does the receipt of each byte restart a timer that has to reach, say 10 ms between bytes, before the event fires?

我问是因为我正在尝试编写一个应用程序来读取来自串行端口的 XML 数据.

I ask because I'm trying to write an app that reads XML data coming in from a serial port.

因为我的笔记本没有串口,所以我用的是虚拟串口模拟器.(我知道,我知道——我对 ATM 无能为力).

Because my laptop has no serial ports, I use a virtual serial port emulator. (I know, I know--I can't do anything about it ATM).

当我通过模拟端口将数据传递到我的应用程序时,每个 XML 记录(大约 1500 字节)都会触发一次事件.完美的.但是,当另一个办公室的同事尝试使用通过实际电缆连接的两台计算机时,DataReceived 事件会在每 10 个左右的 XML 字节之后重复触发,这完全会导致应用程序崩溃.

When I pass data through the emulated port to my app, the event fires once for each XML record (about 1500 bytes). Perfect. But when a colleague at another office tries it with two computers connected by an actual cable, the DataReceived event fires repeatedly, after every 10 or so bytes of XML, which totally throws off the app.

推荐答案

DataReceived 可以随时触发一个或多个字节准备读取.确切的触发时间取决于操作系统和驱动程序,并且在 .NET 中接收数据和触发事件之间也会有一个小的延迟.

DataReceived can fire at any time one or more bytes are ready to read. Exactly when it is fired depends on the OS and drivers, and also there will be a small delay between the data being received and the event being fired in .NET.

您不应该依赖 DataReceived 事件的时间来控制流.

You shouldn't rely on the timing of DataReceived events for control flow.

相反,解析底层协议,如果您没有收到完整的消息,请等待更多.如果您收到多条消息,请确保不要解析第一条消息,因为它们将成为下一条消息的开始.

Instead, parse the underlying protocol and if you haven't received a complete message, wait for more. If you receive more than one message, make sure to keep the left overs from parsing the first message because they will be the start of the next message.

这篇关于是什么导致 .NET SerialPort 类 DataReceived 事件触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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