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

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 call 完成工作?有没有更好的方法?

最佳答案

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

但是,如果您之间有一些代码,则可以使用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

UPDATE :

但是,在Qt Realm 中,您可能想使用 QtConcurrent::run QFuture 以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...

关于c++ - Qt异步调用:如何在异步调用完成其工作后运行某些内容,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51587091/

10-11 00:27