Measuring QNetworkAccessManager download time with QElapsedTimer
-
Good day, colleagues!
I'm trying to measure download time with the help of QElapsedTimer and get this error:
Warning: QObject::startTimer: timers cannot be started from another thread
Here is the simplified code:
@
class Download_Tester {
Q_OBJECT
...
private:
QNetworkAccessManager network_manager_;
QElapsedTimer * timer_;
...
};void Download_Tester::Launch_Test () {
timer_->start(); network_manager_.get (QNetworkRequest(QUrl(url_string)));
}
void Download_Tester::Process_Download (QNetworkReply * reply) {
int time = timer_->elapsed();
...
}@What can cause this behaviour?
Update - I use Download_Tester class from non-main thread. When I completely remove QElapsedTimer from the Download_Tester, the error remains the same - QElapsedTimer is not the reason of the problem.
-
I solved the problem by dynamically creating QNetworkAccessManager for each test run and deleting it after test is finished:
@class Download_Tester {
Q_OBJECT
...
private:
QNetworkAccessManager * network_manager_;
QElapsedTimer * timer_;
...
};void Download_Tester::Launch_Test () {
network_manager_ = new QNetworkAccessManager; timer_->start(); network_manager_->get (QNetworkRequest(QUrl(url_string)));
}
void Download_Tester::Finish_Test () {
delete network_manager_;
}@But is it right to do that? QT 4.7 docs says "One QNetworkAccessManager should be enough for the whole Qt application."
-
Hmm, for this case, I agree, threads are not neccessary. But besides Download_Tester I have another testers (all testers inherit same base class), some of them do heavy computations and freeze the GUI.
So, for the unification of my code, I run every tester in thread different from main.
-
We have a project here using shared NAM between threads and we didn't see this issue.
You can check in
- which thread is living which object (that's a property of QObject)
- that you actually start/stop your timer in the same thread
- that your connection between the networkReply is not in direct mode
From what we've seen here (Qt 4.6.2), it works flawlessly if no one messes with threading àla Qt and use signals/slots instead of calling directly the slot as a function
Please note as well that thread in which network reply lives is a technical thread spawned by network access manager (thus the ->deleteLater to destroy a network reply and the need to connect in automatic or queued mode)