C #: timeout in SerialPort.Open?

I have an autodetect stream that tries to open the ports in order and match the received data, thereby discovering the port where the corresponding device sends the data. Now there are several ports where SerialPort.Open just hangs the stream for ~ 30 seconds. How to set timeout in function SerialPort.Open?

+6
c # serial-port
source share
4 answers

From MSDN
Only one open connection can exist for each SerialPort object.

The best practice for any application is to wait some time after calling the Close method before trying to call the Open method, since the port cannot be closed immediately.

When you call Close (), this workflow takes time to rotate and exit. The required amount of time is not indicated, and you cannot verify that this has been done. All you can do is wait at least one second before calling Open () again.

+3
source share

I am having the same problem and I hope that my solution will help you.

You can detect serial ports in a separate thread, which will be interrupted after 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 !"; } } } } 

Possible improvements may be added to the solution. You can use multi-Thread to speed up the process and use the ProgressBar to clearly display progress.

+2
source share

Add this to your code:

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

And I suggest you see the SerialPort.Open Method

+1
source share

If you understand correctly, you want to read data from the serial port even after a timeout has occurred.

If so, then you should catch a TimeoutException and continue the loop. e.g. MSDN CODE

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

All Articles