zoukankan      html  css  js  c++  java
  • 使用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的参数传入。

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

  • 相关阅读:
    Vue中 el-table大数据量加载,不分页,节省内存的性能优化
    http请求中Content-Type以及qs.stringify的使用
    setTimeout用法(Event Loop简介、for循环中应用、vue中应用)
    Vue中关于图片路径配置的填坑日记
    WebSocket
    Vue中mockjs的使用
    Vue 作用域插槽slot slot-scope v-slot
    Windows Server 2003搭建邮件服务器
    Exchange 2010的部署
    Exchange 2010 详细安装步骤
  • 原文地址:https://www.cnblogs.com/vectorli/p/4744339.html
Copyright © 2011-2022 走看看