How to tell QThread to wait until work is done ,and then finish?

前端 未结 2 1126
臣服心动
臣服心动 2021-01-27 02:28

I have a simple application that uses one worker thread. This worker thread is started and initializes DownloadManager, which is responsible for downloading files from the net.

2条回答
  •  Happy的楠姐
    2021-01-27 02:43

    In cases when you have a signal that is emitted when an asynchronous operation is completed, you can always use QEventLoop to "turn" the asynchronous operation into synchronous with the current thread. It is still asynchronous, but the thread will "wait" for it to finish.

    QNetworkAccessManager nam;
    QEventLoop loop;
    QNetworkReply *reply = nam.get(request); 
    connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
    loop.exec();
    

    So basically you put this in you DownloadManager class where you want to do a network request synchronously. exec() will return once the loop's quit slot has been called.

提交回复
热议问题