為了避免主界面的卡頓等問題,所有的網絡操作都應該放到工作線程中執行。
這種需求帶來的一個問題就是編碼的不方便,如果要把工作的內容單獨寫到一個類或方法里面然后創建線程來執行會給編碼和維護帶來很大的麻煩。
QT提供了一種線程池技術來解決這個問題,把一些需要在單獨線程中執行的操作放到線程池中執行,可以避免手動創建線程的繁瑣,也便於維護。而QtConcurrent則提供了一種可以把lambda表達式直接放到線程中執行。
方法為:
QFuture<T> QtConcurrent::run(Function function, ...)
Equivalent to
QtConcurrent::run(QThreadPool::globalInstance(), function, ...);
Runs function in a separate thread. The thread is taken from the global QThreadPool. Note that function may not run immediately; function will only be run once a thread becomes available.
T is the same type as the return value of function. Non-void return values can be accessed via the QFuture::result() function.
Note that the QFuture returned by QtConcurrent::run() does not support canceling, pausing, or progress reporting. TheQFuture returned can only be used to query for the running/finished status and the return value of the function.
具體使用的時候可以把需要執行的操作封裝到一個函數中,然后把對象的指針傳入lambda表達式中,在lambda里面通過該對象執行函數操作,很簡潔直觀
比如:
Class C
{
void func(const QString& url)
{
//執行網絡通信等操作
}
void funcCaller()
{
QString url = "abc"
QtConcurrent::run([this, url](){
func(url);
});
}
}
也可以把一些函數參數作為lambda的參數傳入。
注意:不能直接在工作線程中創建界面相關的內容。需要向界面對象發送信號在主線程中創建。