在Qt中,我需要连接并检查多个服务器上的更新,为此我正在使用QNetworkAccessManager。问题是我不想连接到下一个URL,直到当前请求已经回复并完成。我的第一个想法是使用如下的循环,但后来我遇到了问题,我不想连接到下一个url,直到当前完成。
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) {
//做更多的事情 }
我解决这个问题的另一个想法就是建立起来:
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
}
现在,在当前网址完成之前,不会请求下一个网址。这个解决方案的问题是我遇到了一些问题,因为很多connection()和finishedSlot()会在我用这些方法创建的东西被打开的同时打开,这会导致内存问题。我知道它与query.exec(sqlString)有关,因为如果没有这个,一切都会像它应该的那样工作。但为什么这两种解决方案之间存在这么大差异呢?
你会如何解决这个问题?
答案 0 :(得分:0)
从finished()插槽启动新请求听起来不错。 只需确保在其中一个回复完成后也回复&gt; deleteLater()。