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

时间:2018-07-30 04:46:17

标签: c++ qt asynchronous

我有类似以下代码的代码,可以进行异步调用:

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呼叫完成工作?有更好的方法吗?

1 个答案:

答案 0 :(得分:2)

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

但是,如果您之间有一些代码,则可以使用C ++ 11的std::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领域中,您可能想使用QtConcurrent::runQFuture以Qt方式进行操作。

这里是例子:

#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...