确保 QSerialPort.close 在程序执行完成之前完成?

Ensuring QSerialPort.close completes before program execution finishes?

我有一个使用 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() 应该执行多长时间?我怎样才能确保它完成?

将您的 closePort 函数设为插槽并将其连接到 QCoreApplication::aboutToQuit:

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

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

还有:

How long should QSerialPort.close() take to execute? And how can I ensure it completes?

同一线程中的槽是同步调用的,因此在控制 returns 到应用程序之前,它可以根据需要花费任意长的时间。该应用程序不会退出,直到您的插槽 returns.