QThread和notify的实现

QThread and implementation of notify

在多线程Qt应用程序中重新实现notify函数需要注意什么? 这是一个示例实现。 目前没有错误,但我担心会出现错误,因为Qt中的多线程使用信号槽进行通信,使用通知功能。

TApplication::notify(QObject *receiver, QEvent *event)
{
    bool returnValue(false);
    try
    {
        returnValue = QApplication::notify(receiver, event);
    }
    catch (IExceptionBase& e)
    {
        if (!fMain.isNull())
        {
            //report error to output and file log
        }
        else
        {
            //report error to output
        }
    }
    catch (...)
    {
        if (!fMain.isNull())
        {
            //report error to output and file log
        }
        else
        {
            //report error to output
        }
    }
    return returnValue;
}

fMain 是一个具有报告功能的模块

在Qt5中,这是安全的。然而,from the documentation,在 Qt6 中,这将不再在主线程之外工作,事实上,该函数正在考虑在 Qt6 中完全弃用。

正如 Kuba Ober 指出的那样,重新实现 notify 来捕获异常是一个坏主意,因为其他线程中的事件和任何排队的信号都是异步传递的。

捕获 notify 中的所有异常是一种反模式。过去这样做很酷,但后来证明是个坏主意。所以不要那样做。如果您的插槽或事件处理程序抛出异常,请将它们的代码包装在 try-catch 块中。 notify 给你一种错误的安全感,因为在很多情况下,信号和直接连接的槽恰好是从事件处理程序中调用的。但有时情况并非如此,您的代码会由于未处理的异常而崩溃。

确保您熟悉 Core C++ Error Handling Guidelines and C++ Exceptions and Error Handling FAQ