0

由于未来的异步,我的代码有时会崩溃。

这不是生产代码,只是演示我想要做的非常简单的东西。

我必须下载一些信息,然后返回第一个获得的结果。试想一下,我不想等待,所以我使用QFutureWatcher的下载速度太快了。

当我获得结果(first或第二个instance)时,我想立即返回结果(我的意思是我不想使用QFutureWatcher::waitForFinished。(如果我从first实例接收到完成的信号,我不再需要那个second。或者对于first.

在生产代码功能中,download我无法访问QNetworkReply,因此无法中止待处理的请求。

有时此代码会崩溃。我究竟做错了什么?

#include <QFutureWatcher>
#include <QtConcurrent>
#include <QEventLoop>
#include <QTimer>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QNetworkAccessManager>

QByteArray download(const QUrl &url)
{
    QNetworkAccessManager manager;
    QNetworkRequest req(url);
    req.setAttribute(QNetworkRequest::SynchronousRequestAttribute, true);
    QNetworkReply *reply = manager.get(req);
    reply->deleteLater();
    return reply->readAll();
}

QByteArray downloadSmth(const QUrl &urlFirst, const QUrl &urlSecond)
{
    typedef QFutureWatcher<QByteArray> FutureWatcher;
    FutureWatcher *first = new FutureWatcher;
    FutureWatcher *second = new FutureWatcher;

    QByteArray res;

    QEventLoop loop;
    QObject::connect(first, &FutureWatcher::finished, [&res, &loop, first] {
        res = first->result();
        loop.quit();
    });
    QObject::connect(second, &FutureWatcher::finished, [&res, &loop, second] {
        res = second->result();
        loop.quit();
    });
    QTimer timer;
    timer.setSingleShot(true);
    QObject::connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit);



    first->setFuture(
        QtConcurrent::run([&urlFirst] {
            return download(urlFirst);
        }));

    second->setFuture(
        QtConcurrent::run([&urlSecond] {
            return download(urlSecond);
        }));


    timer.start(60 * 1000);
    loop.exec();

    if (timer.isActive()) {
        timer.stop();
    }

    first->deleteLater();
    second->deleteLater();
    return res;
}
4

0 回答 0