In Qt I need to connect and check for updates on several servers and for this I'm using QNetworkAccessManager. The problem is that I don't want to connect to the next url until the current request has replied and is finished. My first idea was to use a loop like below, but then I have the problem with that I don't want to connect to the next url until the current is finished.
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 instead:
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 before the current url is finished. The problem with this solution is that I have some problems with that as many connection() and finishedSlot() will be opened at the same time the stuff that I create in these methods wont get deleted and this will cause memory problems. I know it has something to do with query.exec(sqlString), because without this everything works like it should. But why would this differ so much between these two solutions?
How would you solve this?