2

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

现在在当前 url 完成之前不会请求下一个 url。这个解决方案的问题是我有一些问题,因为许多connection()和finishedSlot()将同时打开,我在这些方法中创建的东西不会被删除,这将导致内存问题。我知道它与 query.exec(sqlString) 有关,因为没有它,一切都会像它应该的那样工作。但是为什么这两种解决方案之间会有如此大的差异呢?

你会如何解决这个问题?

4

1 回答 1

0

从 finished() 槽启动新请求听起来不错。只需确保在其中一个回复完成时也执行 reply->deleteLater() 。

于 2010-04-22T14:48:48.557 回答