C#:SerialPort.Open 超时?
我有一个自动检测线程,尝试按顺序打开端口并匹配接收到的数据,从而检测相关设备发送数据的端口。现在,在某些端口上,SerialPort.Open 只是将线程挂起约 30 秒。如何设置 SerialPort.Open 函数的超时?
I have an autodetect thread that tries to open the ports in order and match the received data, thus detecting the port where the relevant device sends the data. Now, there are some ports where the SerialPort.Open simply hangs the thread for ~30 secs. How can I set a timeout on the SerialPort.Open function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
来自 MSDN
每个 SerialPort 对象只能存在一个打开的连接。
对于任何应用程序来说,最佳实践是在调用 Close 方法之后等待一段时间,然后再尝试调用 Open 方法,因为端口可能不会立即关闭。
当您调用 Close() 时,该工作线程需要时间来旋转并退出。未指定所需的时间,您无法验证是否已完成。您所能做的就是在再次调用 Open() 之前等待至少一秒钟。
From MSDN
Only one open connection can exist per SerialPort object.
The best practice for any application is to wait for some amount of time after calling the Close method before attempting to call the Open method, as the port may not be closed instantly.
When you call Close(), this worker thread needs time to spin down and exit. The amount of time needed is not specified and you can't verify that it was done. All you can do is wait at least one second before you call Open() again.
我遇到了同样的问题,希望我的解决方案可以帮助你。
您可以在单独的线程中检测串行端口,该线程将在 500 毫秒后中止。
可以将可能的改进添加到解决方案中。您可以使用多线程来加速进程,并使用
ProgressBar
来清晰地显示进度。I encountered the same problem and I hope my solution can help you.
You can detect the Serial Ports in a separate thread, which will be aborted in 500 ms.
Possible improvements could be added into the solution. You can use multi-Thread to accelerate the process and use
ProgressBar
to display the progress clearly.在您的代码中添加此内容:
我建议您查看 串口.打开方法
Add this in your code:
And I suggest you to see SerialPort.Open Method
如果我理解正确的话,即使发生超时,您也希望从串行端口读取数据。
如果是这样,那么您应该捕获 TimeoutException 并继续循环。例如 MSDN 代码
If I understood you correctly, you wish to read data from the serial port even after timeout occurred.
If so, then you should catch the TimeoutException and continue your loop. e.g. MSDN CODE