C#:SerialPort.Open超时?

我有一个自动检测线程,它尝试按顺序打开端口并匹配接收到的数据,从而检测相关设备发送数据的端口。 现在,有一些端口,SerialPort.Open只挂起线程约30秒。 如何在SerialPort.Open函数上设置超时?

来自MSDN
每个SerialPort对象只能存在一个打开的连接。

任何应用程序的最佳实践是在尝试调用Open方法之前等待一段时间后再调用Close方法,因为端口可能不会立即关闭。

当您调用Close()时,此工作线程需要时间来降速并退出。 未指定所需的时间,您无法validation是否已完成。 您所能做的就是等待至少一秒钟,然后再次调用Open()。

我遇到了同样的问题,希望我的解决方案可以帮到你。

您可以在单独的线程中检测串行端口,该线程将在500 ms内中止。

 // the Serial Port detection routine private void testSerialPort(object obj) { if (! (obj is string) ) return; string spName = obj as string; SerialPort sp = new SerialPort(spName); try { sp.Open(); } catch (Exception) { // users don't want to experience this return; } if (sp.IsOpen) { if ( You can recieve the data you neeed) { isSerialPortValid = true; } } sp.Close(); } // validity of serial port private bool isSerialPortValid; // the callback function of button checks the serial ports private void btCheck(object sender, RoutedEventArgs e) { foreach (string s in SerialPort.GetPortNames()) { isSpValid = false; Thread t = new Thread(new ParameterizedThreadStart(testSerialPort)); t.Start(s); Thread.Sleep(500); // wait and trink a tee for 500 ms t.Abort(); // check wether the port was successfully opened if (isSpValid) { textBlock1.Text = "Serial Port " + s + " is OK !"; } else { textBlock1.Text = "Serial Port " + s + " retards !"; } } } } 

可以在解决方案中添加可能的改进。 您可以使用multithreading来加速进程并使用ProgressBar清楚地显示进度。

在您的代码中添加:

 commPort = new SerialPort(); commPort.ReadTimeout = 1000000; commPort.WriteTimeout = 1000000; 

我建议你看看SerialPort.Open方法

如果我理解正确,即使发生超时,您也希望从串口读取数据。

如果是这样,那么你应该捕获TimeoutException并继续循环。 例如MSDN CODE

 public static void Read() { while (_continue) { try { string message = _serialPort.ReadLine(); Console.WriteLine(message); } catch (TimeoutException) { } } }