tags:

views:

884

answers:

3

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
already done...
gdario
Ok, I hope this help another one ;)
Nathan Campos
why not `SerialPort.InfiniteTimeout` then
Tzury Bar Yochay
Right method but I think the wrong constants - this waits 1000 seconds. Set timeout to 2000 msec or so.
Henk Holterman
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
You don't seem to understand. "SerialPort.Open simply hangs the thread for ~30 secs". This is the porblem.
gdario
sorry, shall I delete this answer then?
Tzury Bar Yochay
No, it will be useful for someone else.
gdario
+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