使用QtConcurrent在线程池中执行网络操作

为了避免主界面的卡顿等问题,所有的网络操作都应该放到工作线程中执行。

这种需求带来的一个问题就是编码的不方便,如果要把工作的内容单独写到一个类或方法里面然后创建线程来执行会给编码和维护带来很大的麻烦。

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里面通过该对象执行函数操作,很简洁直观

比如:

  1. Class C
  2. {
  3.    void func(const QString& url)
  4.    {
  5.        //执行网络通信等操作
  6.    }
  7.    void funcCaller()
  8.    {
  9.        QString url = "abc"
  10.        QtConcurrent::run([this, url](){
  11.           func(url);
  12.        });
  13.    }
  14. }

 

​也可以把一些函数参数作为lambda的参数传入。

 

​注意:不能直接在工作线程中创建界面相关的内容。需要向界面对象发送信号在主线程中创建。

posted @ 2015-08-20 10:25  Jax.Li  阅读(3125)  评论(0编辑  收藏  举报