简体   繁体   English

C#强制要触发SerialPort.DataReceived事件

[英]C# Force SerialPort.DataReceived event to fire

Like many people, I'm having issues with the DataReceived event not firing. 像许多人一样,我遇到了DataReceived事件没有触发的问题。

After working with it, I wrapped my handling processes under the the BytesToRead count, so if I miss a fire, I can pick up where I left off. 使用它之后,我将处理过程包装在BytesToRead计数下,所以如果我错过了火,我可以在我离开的地方继续。 Seemed like it would fix all my issues. 看起来它会解决我所有的问题。

The problem is, sometimes it doesn't trigger even once. 问题是,有时它甚至不会触发一次。 Depending on the packet being sent back, this could be absolutely critical, forcing me to restart the application and the setup process because it relies on being able to process a response. 根据发回的数据包,这可能是绝对关键的,迫使我重新启动应用程序和设置过程,因为它依赖于能够处理响应。

Reading through some of the responses to similar questions hasn't gotten me any closer to guaranteeing that the event will fire at minimum requirements. 通过对类似问题的一些回答阅读并没有让我更接近保证事件将以最低要求激发。 Microsoft mentions the issue with DataReceived not being guaranteed to fire for every byte, but I noticed this above: 微软提到DataReceived无法保证为每个字节触发的问题 ,但我注意到了上述情况:

The DataReceived event is also raised if an Eof character is received, regardless of the number of bytes in the internal input buffer and the value of the ReceivedBytesThreshold property. 无论内部输入缓冲区中的字节数和ReceivedBytesThreshold属性的值如何,如果收到Eof字符,也会引发DataReceived事件。

So my question is, can I force an EOF character through my serial connection to force the event to fire? 所以我的问题是,我可以通过串行连接强制EOF角色强制事件发生吗? What would this character be, 0x1A? 这个角色是什么,0x1A?

If I can't force an EOF character through serial, what would my options be? 如果我不能通过连续强制EOF角色,我的选择是什么? My first thought was maybe create a Task to keep a watch for the event triggering, and if it doesn't trigger, to trigger the actions through the Task. 我的第一个想法是创建一个任务来监视事件触发,如果它没有触发,则通过任务触发操作。

So I was able to fix my issues, coming out a little wiser. 所以我能够解决我的问题,更明智一点。

From my observations, the ReadBytesThreshold plays a critical part in how effective the event actually is. 根据我的观察, ReadBytesThreshold在事件实际有效性ReadBytesThreshold起着关键作用。 When the threshold is set too low, the serial port has a tendency to get itself confused, and will eventually throw up its hands and give up. 当阈值设置得太低时,串口容易让自己感到困惑,并最终会放弃并放弃。

Setting this closer to the size of my expected data coming in appeared to help ease the burden enough to make the reading fairly consistent. 将其设置得更接近我预期数据的大小似乎有助于减轻负担,使阅读相当一致。

I didn't test my idea of using a Task, but reading further online appeared to answer my question about using 0x1A : from what I noticed, it will trigger if it receives this character (at least on a Windows machine). 我没有测试我使用任务的想法,但是在线阅读似乎回答了我关于使用0x1A问题:从我注意到的,如果它接收到这个字符(至少在Windows机器上)它将触发。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM