QNetworkAcdessManager not working as expected



  • Hi guys :)
    I wrote a little wrapper I called "ControlledDownloader" to download web pages. The class' constructor takes as argument the function which is going to be called when the download finishes.

    Here is the class:

    class ControlledDownloader  {
    
       QNetworkAccessManager nam;
       QNetworkRequest req;
       std::function< void( QNetworkReply* ) > toCall;
    
    public:
    
       ControlledDownloader(const std::function<void(QNetworkReply*)>& _toCall) : toCall(_toCall){
    
            QObject::connect( &nam, &QNetworkAccessManager::finished, [&]( QNetworkReply * reply ){ toCall(reply); } );
    
       }
    
       void getPage( QString url ){
           nam.get( QNetworkRequest(url) );
       }
    
    };
    

    Apparently, when doing something like this:

    ControlledDownloader * c = new ControlledDownloader([](QNetworkReply * reply){qDebug()<<QString(reply->readAll()).split("\n").size();});
    c->getPage("https://forum.qt.io/");
    

    the code works just expected, printing the number of lines in the source code of a page.

    However, I thought this happens in the "background" (asynchronous, if I'm right) so I tried doing something like this:

    ControlledDownloader * c = new ControlledDownloader([](QNetworkReply * reply){qDebug()<<QString(reply->readAll()).split("\n").size();});
       qDebug()<<"start";
       c->getPage("https://forum.qt.io/");
       fibbo(46);
       qDebug()<<"ok";
    

    Fibbo is a recursive implementation of the Fibonacci algorithm, on my system fibbo(46) takes some good seconds to run.
    I expected the following output:

    start
    623 (no. of lines in source code)
    ok
    

    , since the computation of fibbo(46) takes much longer than the download of the qt forum webpage. However, this is the output I get:

    start
    ok
    623
    

    , which means that the actual download begins after fibbo function ends. Therefore, I'm pretty sure I'm missing something important. Could you tell me where is the problem ?


  • Lifetime Qt Champion

    Hi,

    Your fibbo function blocks the main event loop thus breaks the asynchronous nature of Qt. Either move the execution of fibbo to another thread or move the network handling to another thread however fibbo will still block the main thread.



  • Thanks @SGaist . I'll look into threads.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.