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

StackOverflow https://stackoverflow.com/questions/23500898

Question

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.

Was it helpful?

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;
}

OTHER TIPS

When connectToDatabase is called for the first time, you can set a boolean variable to true which shows thatconnectToDatabase is called. In connectToDatabase method you can check for this variable and return if it is true :

void connectToDatabase()
{
    if(!connected)
         connected = true;
    else
         return;

    //...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top