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?
A:
Add this in your code:
commPort = new SerialPort();
commPort.ReadTimeout = 1000000;
commPort.WriteTimeout = 1000000;
And I suggest you to see SerialPort.Open Method
Nathan Campos
2009-11-08 12:30:13
already done...
gdario
2009-11-08 12:31:12
Ok, I hope this help another one ;)
Nathan Campos
2009-11-08 12:32:09
why not `SerialPort.InfiniteTimeout` then
Tzury Bar Yochay
2009-11-08 12:37:58
Right method but I think the wrong constants - this waits 1000 seconds. Set timeout to 2000 msec or so.
Henk Holterman
2009-11-08 12:52:47
A:
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
public static void Read()
{
while (_continue)
{
try
{
string message = _serialPort.ReadLine();
Console.WriteLine(message);
}
catch (TimeoutException) { }
}
}
Tzury Bar Yochay
2009-11-08 12:33:01
You don't seem to understand. "SerialPort.Open simply hangs the thread for ~30 secs". This is the porblem.
gdario
2009-11-08 12:35:02
+1
A:
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.
SwDevMan81
2009-11-08 13:35:13