QPromise/QFuture and QMetaObject::invokeMethod
-
Hey
I'm trying to do this >
QFuture<int> icServerHTTP::startServer(const quint16 port) noexcept { QPromise<int> promise; if (thread() != QThread::currentThread()) { QFuture<int> future = promise.future(); QMetaObject::invokeMethod(this, [this, port, promise = std::move(promise)]() mutable { try { int result = _startServer(port); promise.addResult(result); promise.finish(); } catch (...) { promise.setException(std::current_exception()); } }, Qt::QueuedConnection); return future; } promise.addResult(_startServer(port)); promise.finish(); return promise.future(); }
I tried wrapping it in smart pointer, but that cause >
Due to memory issues and smart pointer cleaning the obj instead of the future/etc doing it... Ahh tricky...Any idea how to make it work?
Thanks! -
Hi,
What exactly are you trying to put in a smart pointer ?
Which one is it ?
How are you trying to do it ? -
I tried to put promise in smart pointer.
In general I cant pass promise to invokeMethod. The concept is that if I run in correct thread, I want it to just run normally, but if not, I need it to execute in correct thread, but I still want to be able to wait for it to finish/get correct result out of it. Atm this crashes.
I keep hitting those issues more and more, asking it to execute in another thread/etc/etc... :/You can run the example above and just instead of putting _startServer(port) just set int to 20 or something like that. But u need to simulate InvokeMethod, I guess you can just run invoke method regardless/ignore thread check to reproduce the problem... Like this >
QPromise<int> promise; QFuture<int> future = promise.future(); QMetaObject::invokeMethod(this, [this, port, promise]() mutable { try { // Call startServer on the correct thread int result = 10; // Set the result to the promise promise.addResult(result); promise.finish(); } catch (...) { // Handle any exceptions and set as failure in promise promise.setException(std::current_exception()); } }, Qt::QueuedConnection); return future;
-
Isn't QFuture::unwrap what you are looking for ?
-
Isn't QFuture::unwrap what you are looking for ?
-
In that case, shouldn't you be using the
then
method to call your custom function ?