何时决定从串行端口设备读取 StreamReader 中的下一个字符以避免出现 Timeour Error (C#)
我向串行端口中的设备发送重置连接命令。作为回应,我有时(大多数时候)会得到一个字符的答案。因此,我在使用流编写器编写第一个命令后使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
可能只是捕获异常并通过将数据包发送到设备以获得响应来再次迭代。这就是大多数设备驱动程序所做的。可能是您限制了重试次数。
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.
如果您有响应 SerialPort.DataReceived 事件的方法,您可以在其中尝试类似的操作:
有关 DataReceived 事件的更多信息:MSDN 上的 DataReceived
If you have a method that responds to SerialPort.DataReceived event you may try something like this in it:
Further info on DataReceived event: MSDN on DataReceived