SerialPort DataReceived Event 会重复触发吗?
假设只要有 100 个字节可用,我就从 SerialPort 读取数据,否则什么也不做。这意味着,串行端口缓冲区中的剩余数据仍然可用。此读取是在 DataReceived 的事件处理程序内完成的。
现在假设出现一种情况,例如 SerilaPort 缓冲区中有 50 个字节,但没有更多数据到来。据我了解,只要有一定数量的字节可用于从缓冲区读取,就会触发 DataReceived 事件。
现在,在给定的场景中,如果我从未读取过这 50 个字节,事件是否会因为这些未读字节的存在而被持续激活?
Suppose I read data from SerialPort whenever there is 100 bytes available or else nothing is done. That means, the remaining data will still be available in the SerialPort Buffer. This reading is done inside the event handler of DataReceived.
Now suppose a situation arises, when there there is, say 50 bytes in the SerilaPort Buffer and no more data comes. From what I understand, the DataReceived Event will be triggered whenever there is certain amount of bytes available for reading from the Buffer.
Now, in the given scenario, if I never read those 50 bytes, will the Event get activated continuously due to the presence of these unread bytes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我确实发布了答案(参见上面的评论)。它在文档中。 “ ...当从 SerialPort 对象接收到数据时。”
OP 说“如果我从未读取过这 50 个字节,事件是否会因为这些未读字节的存在而被持续激活?”你回答说:“是的,它会一直触发,直到你调用 Read()。”
仅当收到新数据时才会触发该事件。如果不处理该数据,该数据将不会引发新事件。但是,如果有新数据到达,则会触发一个新事件,然后您可以处理所有数据。
I did post the answer(see comments above). It is in the documentation. " ...when data is received from the SerialPort object."
The OP said "if I never read those 50 bytes, will the Event get activated continuously due to the presence of these unread bytes?" and you replied "Yes, it will keep firing until you call Read()."
The event only fires whenever new data is received. If you do not process that piece of data, that piece of data will NOT cause a new event. However, if new data arrives, a new event will fire and you can then process it all.
是的,当有额外的字节进入时,它会继续触发,直到您调用 Read()。您可以使用 ReceivedBytesThreshold 属性来延迟该过程。这通常是一个坏主意,由于溢出错误而丢失一个字节可能会导致通信完全占用。自己在事件处理程序中缓冲您 Read() 的内容。
另请注意,这只是 Microsoft 串行端口驱动程序的已知行为。 SerialPort 类使用 WaitCommEvent API 函数,由驱动程序来实现它。特别是大量的 USB 驱动程序模拟串行端口,以便轻松连接到自定义设备,但它们的创建方式并不相同。
Yes, it will keep firing when additional bytes come in until you call Read(). You could use the ReceivedBytesThreshold property to delay that. This is usually a bad idea, losing a byte due to an overrun error could cause communications to seize completely. Buffer what you Read() in the event handler yourself.
Also beware that this is only the known behavior of the Microsoft serial port driver. The SerialPort class uses the WaitCommEvent API function, it is up to the driver to implement this. Especially the plethora of USB drivers that emulate a serial port to make it easy to interface to a custom device are not created equal.
我认为这证明了我的观点,对 VB 代码感到抱歉。
调试输出
I think this proves my point, sorry for the VB Code.
Debug output