Qt异步调用:如何在异步调用完成其工作后运行某些内容

用户名

我有下面的代码,它执行异步调用:

QMetaObject::invokeMethod(this, "endSelectionHandling", Qt::QueuedConnection);

我想这样修改代码:

QMetaObject::invokeMethod(this, "endSelectionHandling", Qt::QueuedConnection);

// I want to add statements here which depend on the result of the above async call.
// How can I wait for the above async call to finish its jobs?

如何等待Qt asycn呼叫完成工作?有没有更好的方法?

阿泽姆

在您的问题中,您看起来根本不需要异步调用,因为在进行异步调用之后您正在等待结果。

但是,如果您之间有一些代码,则可以使用C ++ 11std::async异步调用该函数,然后std::future在执行其他操作后随时随地在需要它的结果时等待它

这是一个例子:

#include <iostream>
#include <future>
#include <thread>
#include <chrono>

#define LOG()    std::cout << __func__ << " : "

void test()
{
    LOG() << "IN\n";

    using namespace std::chrono_literals;
    std::this_thread::sleep_for( 1s );

    LOG() << "OUT\n";
}

int main()
{
    LOG() << "Calling test()...\n";

    auto f = std::async( std::launch::async, test );

    LOG() << "Running test()...\n";

    // ...                             ...
    // ... You can do other stuff here ...
    // ...                             ...

    f.wait(); // Blocking call to wait for the result to be available

    LOG() << "Exiting...\n";

    return 0;
}

这是输出:

main : Calling test()...
main : Running test()...
test : IN
test : OUT
main : Exiting...

这是实时示例:https : //ideone.com/OviYU6

更新

但是,在Qt领域中,您可能想以Qt方式使用QtConcurrent::runQFuture做事。

这是示例:

#include <QDebug>
#include <QtConcurrent>
#include <QFuture>
#include <QThread>

#define LOG()    qDebug() << __func__ << ": "

void test()
{
    LOG() << "IN";

    QThread::sleep( 1 );

    LOG() << "OUT";
}

int main()
{
    LOG() << "Calling test()...";

    auto f = QtConcurrent::run( test );

    LOG() << "Running test()...";

    // ...                             ...
    // ... You can do other stuff here ...
    // ...                             ...

    f.waitForFinished(); // Blocking call to wait for function to finish

    LOG() << "Exiting...";

    return 0;
}

这是输出:

main : Calling test()...
main : Running test()...
test : IN
test : OUT
main : Exiting...

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章