co_await vs QCoro::waitFor()? #210
-
When I'm connecting a Qt signal to a coroutine, does it make more sense to co_await the coroutine, or to use QCoro::waitFor? For example, I have a class with member function that (ultimately) uses QIODevice to send a request and wait for response that I want to call at a certain interval:
or
Is it the same thing? If so, what about taking it a level further? I could either implement
or
The second way is attractive here because it lets me take the lambda out of the original The real thing driving this question is that I was originally connecting signals directly to coroutine lambdas, and letting them get more complicated than just 'call a member coroutine'. I got bit by a use-after-free bug (described here) and I'm doing what I can to get rid of all my capturing coroutine lambdas as advised by the C++ Core Guidelines here |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi, regarding But trhanks to the nature of QCoro's coroutines, you should be able to do connect( &timer, &QTimer::timeout, this, &ThisClass::request_data_from_serial);
There's also a third option: QByteArray DeviceComm::request_data_from_serial()
{
return QCoro::waitFor(send_request().then([this]() {
return get_response();
}));
} Using Just to showcase void DeviceComm::request_data_from_serial(Callback callback)
{
send_request().then([this]() {
return get_response();
}).then([this, callback = std::move(callback)](const QByteArray &response) {
callback(response);
});
} There are many more variations possible of course, depends on your API design etc. |
Beta Was this translation helpful? Give feedback.
Hi,
regarding
QCoro::waitFor()
, there's one thing to consider:QCoro::waitFor()
internally runs a nestedQEventLoop
- and it's always better to avoid nestedQEventLoop
s due to potential re-entrancy issues. The construction of nestedQEventLoop
and the handling of things adds a small overhead, so it would make coroutines slightly more expensive.But trhanks to the nature of QCoro's coroutines, you should be able to do
QCoro::Task
is an eager coroutine (it starts automatically when called, it doesn't need to beco_await
ed) and is designed specifically to run to its completion even when notco_await
ed.QCoro::wai…