何时决定从串行端口设备读取 StreamReader 中的下一个字符以避免出现 Timeour Error (C#)

发布于 2024-11-29 12:45:16 字数 480 浏览 1 评论 0原文

我向串行端口中的设备发送重置连接命令。作为回应,我有时(大多数时候)会得到一个字符的答案。因此,我在使用流编写器编写第一个命令后使用 reader.Read comment 。但有时我们的设备不会发送对第一个请求的响应。这对我来说并不重要,因为我不在我的软件中使用响应。我将继续向设备发送下一个命令。当设备不发送响应时,我的 reader.Read 调用出现超时异常,我无法继续与设备通信。由于我不知道设备何时会应答请求,我该怎么办?我要么不读第一个答案。但在这种情况下,一个字符会破坏设备将发送给我的以下消息。它将位于消息的开头。如果我使用 reader.read 我会得到超时异常。 我尝试过

if (reader.Peek() >= 0)
   reader.Read();

但这对我没有帮助。此时 Peek() 方法会出现超时异常。 我如何知道是否有适合我的字符,或者我是否必须跳过阅读并继续编写下一个命令?

谢谢您的回答, 费尔达·奥兹德米尔

I send a reset connection command to a device in serial port. And In response to that i sometimes (most of the time) get a one character answer. So I use reader.Read comment after writing the first command using a streamwriter. But sometimes our device does not send a response to this first request. It is not matter for me cause i don't use the response in my software. I will just go on sending the next commands to the device. When the device does not send a response my reader.Read call gets a timeout exception and i can not go on communicating with the device. Since i don't know when the device will answer the request or not what can i do? I can either not read the first answer. But in that case the one character spoils the the following messages that the device will send me. It will be in the beginning of the message. If i use reader.read i can get timeout exception.
I tried

if (reader.Peek() >= 0)
   reader.Read();

But it didn't help me. That time Peek() method can get timeout exception.
How will i know if there is a character for me, or if i have to skip reading and continue to writing the next command??

Thank you for your answers,
Ferda Ozdemir

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

忆梦 2024-12-06 12:45:16

可能只是捕获异常并通过将数据包发送到设备以获得响应来再次迭代。这就是大多数设备驱动程序所做的。可能是您限制了重试次数。

May be just catch the exception and iterate once again by sending the packet to the device for a response. Thats what most device drivers do. May be you limit the number of retries you do.

雪落纷纷 2024-12-06 12:45:16

如果您有响应 SerialPort.DataReceived 事件的方法,您可以在其中尝试类似的操作:

while (port.BytesToRead > 0)
{
    reader.Read(); //Or reader.ReadLine(); 
}

有关 DataReceived 事件的更多信息:MSDN 上的 DataReceived

If you have a method that responds to SerialPort.DataReceived event you may try something like this in it:

while (port.BytesToRead > 0)
{
    reader.Read(); //Or reader.ReadLine(); 
}

Further info on DataReceived event: MSDN on DataReceived

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文