1. 程式人生 > >QT技巧 - 非同步非阻塞轉為同步阻塞的方法

QT技巧 - 非同步非阻塞轉為同步阻塞的方法

QT技巧 - 非同步非阻塞轉為同步阻塞的方法


如需轉載請標明出處:http://blog.csdn.net/itas109
QQ技術交流群:129518033

目錄

文章目錄

環境:
QT版本:5.6.2
VS版本:VS2013
系統版本:windows 7 64bit


前言

QT中一般都推薦使用非同步的方式,因為訊號與槽是QT的核心。但是,有些時候我們需要等待一個返回結果之後,才能執行下一步操作。當然,我們可以在返回的槽函式裡面繼續進行下一步操作,但是,這樣不利於程式的解耦。例如,多個部分的UI繪製,必須按照一定順序繪製,那麼如果在槽函式裡面寫下一個UI的繪製,這樣的方式在我們需要刪除其中一個UI繪製時,並不能做到很好的解耦。所以本文介紹一種,將非同步非阻塞請求轉為同步阻塞請求的方法。

1.非同步非阻塞轉為同步阻塞的方法

採用超時 + 迴圈等待的方式,將非同步非阻塞轉為同步阻塞。

啟動一個迴圈,不斷的迴圈檢測是否滿足退出條件,當滿足退出條件(1.超時 2.非同步結果返回),退出迴圈,繼續執行其他操作。

2.程式碼示例

非同步請求函式: void getData();
對應的訊號:void getDataSignal(QString data);
對應的槽:void onGetData(QString data);

int timeout = 3 * 1000; //超時時間
QTimer t;
QEventLoop q;
connect(&t, &QTimer::timeout, &q, &QEventLoop::quit);  //非同步呼叫超時退出
connect(this,&Mainwindow::getDataSignal, &q, &QEventLoop::quit);  //非同步呼叫完成退出
//執行非同步請求
getData();
t.start(timeout);
q.exec();
disconnect(&t, &QTimer::timeout, &q, &QEventLoop::quit);  
disconnect(this,&Mainwindow::getDataSignal, &q, &QEventLoop::quit);
//下一步操作

3.注意事項

QEventLoop需要依賴QCoreApplication或QApplication,如果沒有QCoreApplication或QApplication,需要建立QCoreApplication或QApplication例項。

The QAbstractEventDispatcher class provides an interface to manage Qt's event queue.

An event dispatcher receives events from the window system and other sources. It then sends them to the QCoreApplication or QApplication instance for processing and delivery. QAbstractEventDispatcher provides fine-grained control over event delivery.

Reference:
NULL

覺得文章對你有幫助,可以用微信掃描二維碼捐贈給博主,謝謝!
微信
如需轉載請標明出處:http://blog.csdn.net/itas109
QQ技術交流群:129518033