This repository has been archived on 2024-07-22. You can view files and clone it, but cannot push or open issues or pull requests.
Doric/doric-Qt/example/doric/async/DoricAsyncCall.h

49 lines
1.2 KiB
C
Raw Normal View History

2021-02-04 16:59:58 +08:00
#ifndef ASYNC_CALL_H
#define ASYNC_CALL_H
2021-02-08 11:37:51 +08:00
#include <QFuture>
2021-02-04 16:59:58 +08:00
#include <QThreadPool>
#include <QtConcurrent/QtConcurrent>
2021-05-25 10:45:45 +08:00
#include "DoricAsyncResult.h"
2021-02-04 16:59:58 +08:00
class DoricAsyncCall {
public:
2021-05-25 10:45:45 +08:00
template <typename Function>
static std::shared_ptr<DoricAsyncResult>
ensureRunInThreadPool(QThreadPool *threadPool, Function &&function) {
std::shared_ptr<DoricAsyncResult> asyncResult =
std::make_shared<DoricAsyncResult>();
Function lambda = std::forward<Function>(function);
QtConcurrent::run(threadPool, [lambda, asyncResult]() {
lambda();
// asyncResult->setResult(result);
});
return asyncResult;
2021-02-04 16:59:58 +08:00
}
2021-02-09 10:38:27 +08:00
template <typename Function>
2021-05-25 10:45:45 +08:00
static std::shared_ptr<DoricAsyncResult>
ensureRunInMain(Function &&function, QThread *thread = qApp->thread()) {
std::shared_ptr<DoricAsyncResult> asyncResult =
std::make_shared<DoricAsyncResult>();
2021-02-22 18:54:29 +08:00
auto *obj = QAbstractEventDispatcher::instance(thread);
Q_ASSERT(obj);
2021-05-25 10:45:45 +08:00
Function lambda = std::forward<Function>(function);
QMetaObject::invokeMethod(obj, [lambda, asyncResult]() {
lambda();
// asyncResult->setResult(result);
});
return asyncResult;
2021-02-09 10:38:27 +08:00
}
2021-02-04 16:59:58 +08:00
};
#endif // ASYNC_CALL_H