C#: Timeout on SerialPort.Open?

不羁岁月 提交于 2019-12-18 04:55:10

问题


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?


回答1:


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.




回答2:


I encountered the same problem and I hope my solution can help you.

You can detect the Serial Ports in a separate thread, which will be aborted in 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 could be added into the solution. You can use multi-Thread to accelerate the process and use ProgressBar to display the progress clearly.




回答3:


Add this in your code:

commPort = new SerialPort();

commPort.ReadTimeout = 1000000;
commPort.WriteTimeout = 1000000;

And I suggest you to see SerialPort.Open Method




回答4:


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) { }
    }
} 


来源:https://stackoverflow.com/questions/1696238/c-timeout-on-serialport-open

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!