C#:SerialPort.Open 超时?

发布于 2024-08-10 05:34:05 字数 120 浏览 2 评论 0原文

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

断桥再见 2024-08-17 05:34:05

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

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

当您调用 Close() 时,该工作线程需要时间来旋转并退出。未指定所需的时间,您无法验证是否已完成。您所能做的就是在再次调用 Open() 之前等待至少一秒钟。

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.

寄意 2024-08-17 05:34:05

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

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

// 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 !";
        }
      }
   }   
}   

可以将可能的改进添加到解决方案中。您可以使用多线程来加速进程,并使用ProgressBar来清晰地显示进度。

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.

云柯 2024-08-17 05:34:05

在您的代码中添加此内容:

commPort = new SerialPort();

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

我建议您查看 串口.打开方法

Add this in your code:

commPort = new SerialPort();

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

And I suggest you to see SerialPort.Open Method

萤火眠眠 2024-08-17 05:34:05

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

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

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

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) { }
    }
} 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文