4

我知道在 4.8 版中,每个 http 请求都有自己的线程来运行。
我正在做一个链接检查器应用程序,它在一段时间循环中执行大量 http 请求,我在 Windows 任务管理器中注意到我的应用程序随着时间的推移使用了 1600 多个线程,并且数量永远不会下降,直到它崩溃应用程序。(我猜这就是原因。)

我的问题是,是否QNetworkAccessManager可以选择使用线程池?
或者它是否可以选择在完成其 http 请求后清理其线程?

这是主循环:

while(!rpm_urlStack->isEmpty())
{
    QString url = rpm_urlStack->top();

    //define the reply
    QNetworkReply *reply;
    rpm_urlStack->pop();

    QString urlForReq(url);

    bool returnVal = true;
    QNetworkRequest request;

    request.setUrl(QUrl(urlForReq));
    request.setRawHeader("User-Agent", USER_AGENT.toUtf8());
    request.setRawHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
    request.setRawHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    request.setRawHeader("Accept-Language", "en-us,en;q=0.5");
    request.setRawHeader("Connection", "Keep-Alive");

    QEventLoop loop;
    reply = m_networkManager->get(request);
    connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
    loop.exit();

    if(!loop.isRunning()) {
        loop.exec();
    }

    RequestFinishedHandler(reply);

    // this is how I delete the reply object
    delete reply;
}

RequestFinishedHandler(QNetworkReply *reply)
{
    if (reply->error() > 0) {
        QNetworkReply::NetworkError networkError = reply->error();
        QString err = reply->errorString();
    } else {
        QVariant vStatusCodeV = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
        QMutexLocker lock(_pMutex); // _pMutex defined as class member
        char *buffer;
        buffer = getCurrentDateTime();
        QTextStream out(m_file);
        out << buffer << "  " << _sCurrentUrl << "\n";
        lock.unlock();

        if(vStatusCodeV.toInt() == 200) {
            QString ApiResponse;
            QByteArray data;
            data=reply->readAll();
            ApiResponse.append(QString::fromUtf8(data));
        }
    }
}
4

1 回答 1

1

看来要有效,必须从事件循环中调用该方法,该方法deleteLater必须重新控制执行以处理垃圾收集。

也许你应该重构你的代码,让事件循环替换你的 while 循环。或者,由于您没有使用插槽来处理回复,也许您可​​以在函数finished结束时直接删除回复。RequestFinishedHandler

于 2012-11-06T22:45:38.707 回答