Background
I have a dialog which runs a time-consuming operation on its initialization. I wrapped this operation into an asynchronous function in order not to freeze the GUI.
Example
Imagine a dialog/widget which shows the current weather fetched asynchronously from a remote server:
Dialog::Dialog()
{
auto label = new QLabel(this);
QtConcurrent::run([=]() {
const int temperature = getWeather(); // Time-consuming function
label->setText(temperature);
});
// The rest code, layouts initialization, etc.
}
Problem
If this dialog/widget is closed before the asynchronous operation is finished, the label->setText()
part will obviously lead to a crash because the widget object won't exist by that moment.
Question
What is the proper way to deal such situations? Probably, I should use something else instead of QtConcurrent
(QThread
, for example) in order to properly cancel the asynchronous function when the dialog is closed.
Note
Note that the actual code is about reading a bunch of files, not about networking, that's why using the async QNetworkRequest
interface is not a case.