【问题标题】:Ensuring QSerialPort.close completes before program execution finishes?确保 QSerialPort.close 在程序执行完成之前完成?
【发布时间】:2016-09-12 00:17:13
【问题描述】:

我有一个使用 QSerialPort 的应用程序,我的程序做的最后一件事就是调用我的 closePort 函数,如下所示:

//Closes the port when we're done with it
void SerialCommSession::closePort()
{
    connected = false;
    if(m_port.isOpen())
    {
        qDebug() << "closing port";
        m_port.close();
    }
}

在某些时候它可以正常工作,并且程序会再次启动而没有任何问题。但可能有 75% 的时间,当我再次尝试运行程序时,它无法打开端口,返回错误代码 2。 QSerialPort.close() 需要多长时间才能执行?我如何确保它完成?

【问题讨论】:

    标签: c++ qt port


    【解决方案1】:

    使您的closePort 函数成为一个插槽并将其连接到QCoreApplication::aboutToQuit

    connect(qApp, &QCoreApplication::aboutToQuit, someCommSessionPointer, &SerialCommSession::closePort)
    

    当事件循环退出并且在应用程序退出之前,您的插槽将被调用。确保您已包含 &lt;QCoreApplication&gt; 或其派生类之一,以使 qApp 宏起作用。

    还有:

    QSerialPort.close() 执行需要多长时间?我如何确保它完成?

    同一个线程中的插槽是同步调用的,因此在控制权返回到应用程序之前,它可能需要尽可能长的时间。在您的插槽返回之前,应用程序不会退出。

    【讨论】:

      猜你喜欢
      • 2019-11-16
      • 2012-08-04
      • 2020-11-02
      • 1970-01-01
      • 2018-02-28
      • 1970-01-01
      • 2016-10-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多