Run multiple url requests in a loop in Qt

In Qt, I need to connect and check for updates on multiple servers, and for that I am using QNetworkAccessManager. The problem is that I don't want to connect to the next url until the current request is answered and completed. My first idea was to use a loop as shown below, but then I have a problem that I don't want to connect to the next url until the current finishes.

void connect() {
    for (int index = 0; index < 20; index++) {
        //I need to use this QSqlQuery to get some data here
        QSqlQuery query;
        QString sqlString = getSql(index);
        query.exec(sqlString);
        .....

        if (needUpdate(index)) { //Check if I need to connect to this url
            QNetworkAccessManager *networkAccessManager = new QNetworkAccessManager(this); 
            connect(networkAccessManager, SIGNAL(finished(QNetworkReply*)),this, SLOT(finishedSlot(QNetworkReply*)));
            QUrl url = getUrl(index); //Get the url based on the current index
            networkAccessManager->get(QNetworkRequest(url));
        }
    }
} 

void finishedSlot(QNetworkReply* reply) {

      

// Do more stuff}

My other idea to solve the problem was to build it like this:

int index;

void connect() {
        /*I need to use this QSqlQuery to get some data here, 
          it works perfect when just looping like before, but when using 
          this solution I get memory problems, 
         it seems like it doesn't delete the query*/
        QSqlQuery query;
        QString sqlString = getSql(index);
        query.exec(sqlString);
        ..... 


    if (needUpdate(index)) { //Check if I need to connect to this url
        QNetworkAccessManager *networkAccessManager = new QNetworkAccessManager(this); 
        connect(networkAccessManager, SIGNAL(finished(QNetworkReply*)),this, SLOT(finishedSlot(QNetworkReply*)));
        QUrl url = getUrl(index); //Get the url based on the current index
        networkAccessManager->get(QNetworkRequest(url));
    } else {
        index++;
        connect(); //Request next url
    }
}

void finishedSlot(QNetworkReply* reply) {
//Do more stuff
    index++;
    connect(); //Request next url
}

      

Now the next url will not be requested until the current url completes. The problem with this solution is that I have some problems with many connections () and finishedSlot () being opened at the same time that the stuff I create in these methods will not be removed and this will cause problems with memory. I know it has something to do with query.exec (sqlString), because without it everything works as it should. But why is this so different from these two solutions?

How would you solve this?

+2


a source to share


1 answer


Launching new requests from a ready () slot sounds good. Just make sure to also answer-> deleteLater () when one of the answers is complete.



0


a source







All Articles