@@ -202,9 +202,17 @@ std::function<QVariant(QVariant)> convertToQVariantFunction(Func&& func);
202202 \b Example:
203203 \code{.cpp}
204204 // Passing `this` into create() will make the thread stop if `this` is deleted before it finishes.
205+ // Though note that `this` could still be deleted during a background action,
206+ // and the thread will only be stopped *after* the action is done, so you must be
207+ // sure to always guard data accessed in background actions with something like
208+ // a std::shared_ptr<T>.
205209 BackgroundThread::create(this)
206210 // Do actions serially in the background
207- ->thenBackground([this](QVariant) {
211+ ->thenBackground([state = m_sharedPtrState](QVariant) {
212+ // Note that state should be accessed through a shared pointer-like structure
213+ // In case our parent gets deleted while we're doing background processing.
214+
215+ // Do our task background here
208216 bool success = SomeLongNetworkOperation();
209217 // Return value will be passed to next action's QVariant parameter
210218 return success;
@@ -217,7 +225,7 @@ std::function<QVariant(QVariant)> convertToQVariantFunction(Func&& func);
217225 // You don't have to return anything (next QVariant param will be QVariant())
218226 })
219227 // You can also combine with a ProgressTask for showing a progress dialog
220- ->thenBackgroundWithProgress(m_window, "Doing Task", "Please wait...", "Cancel", [this ](QVariant var,
228+ ->thenBackgroundWithProgress(m_window, "Doing Task", "Please wait...", "Cancel", [state = m_sharedPtrState ](QVariant var,
221229 ProgressTask* task, ProgressFunction progress) {
222230 progress(0, 0);
223231 DoTask1WithProgress(SplitProgress(progress, 0, 1));
@@ -244,7 +252,7 @@ std::function<QVariant(QVariant)> convertToQVariantFunction(Func&& func);
244252 }
245253 })
246254 // You can also catch in the background
247- ->catchBackground([this ](std::exception_ptr exc) {
255+ ->catchBackground([state = m_sharedPtrState ](std::exception_ptr exc) {
248256 ...
249257 })
250258 // Finally-actions will be run after all then-actions are finished
@@ -257,7 +265,7 @@ std::function<QVariant(QVariant)> convertToQVariantFunction(Func&& func);
257265 }
258266 })
259267 // You can also have finally-actions in the background
260- ->finallyBackground([this ](bool success) {
268+ ->finallyBackground([state = m_sharedPtrState ](bool success) {
261269 ...
262270 })
263271 // Call start to start the thread
0 commit comments