Search code examples
c++qtsignalsblockingslot

Qt-C++ Preventing a slot to execute a method, when a previous slot already dit and has not finished


In my project i have several Objects which gather some data and put them into a database, now for some reasons the database link could fail, so i made signal for it and bound it to a slot which will write what happened in a log file and try to reconnect to the database.

Now the problem is, sometimes it happens that a signal trigger the slot and then try to reconnect to the database while a previous connection is on his way. And as the Objects send several requests in a very small interval this problem happens always, because as soon as a request fails the signal is emitted to re-establish the connection.

So what I want is a proper way to prevent any slot to call the "connectToDatabase()" method when another slot already did it so that the method will end properly.

here is the slot.

void mainFrame::reconnectDatabase(QSqlQuery *failedQuery)
{ 
    log_it("QUERY:\""+failedQuery->lastQuery()+"\" ERROR:\""+failedQuery->lastError().text()+"\"");
    log_it("Re-connecting to Database...");
    QSqlDatabase db = QSqlDatabase::database();
    if(!db.open())
        log_it("Reconnecting database operation failed! REASON: \""+db.lastError().text()+"\"");
}

log_it() is my function for writing logs.


Solution

  • You could accomplish this by having a boolean check indicating that an attempt to connect to the database is already in progress.

    void MyClass::slotConnectToDatabase()
    {
        if (m_connectingToDatabase)
            return;
    
        m_connectingToDatabase = true;
        // connect to database
        m_connectingToDatabase = false;
    }