问题描述
我有一个自动检测线程尝试按顺序打开端口并匹配接收到的数据,从而检测相关设备发送数据的端口.现在,有一些端口 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?
推荐答案
来自 MSDN
每个 SerialPort 对象只能存在一个打开的连接.
From MSDN
Only one open connection can exist per SerialPort object.
任何应用程序的最佳做法是在调用 Close 方法后等待一段时间,然后再尝试调用 Open 方法,因为端口可能不会立即关闭.
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.
当您调用 Close() 时,此工作线程需要时间来减速并退出.未指定所需的时间量,您无法验证它是否已完成.您所能做的就是在再次调用 Open() 之前等待至少一秒钟.
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.
这篇关于C#:SerialPort.Open 超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!