Using background threads for long processes in MFC
It’s not easy to write a Windows program that takes a long time to do something and yet still seems responsive to the user. Consider that you’ve got a single task that needs to be finished:
It’s not easy to write a Windows program that takes a long time to do something and yet still seems responsive to the user. Consider that you’ve got a single task that needs to be finished:
```c++ // task.h class TaskObserver;
Initially, we’ll run this as a foreground task. This will ensure that the code compiles and works before we get too complicated. Also, it’ll show why we want this task to run as a background thread.
We can deal with the first one (no feedback), by using an hourglass:
Because we have progress reporting, we can make use of a progress dialog to partially solve all of these problems. In Visual C++, select “Project|Add To Project|Components and Controls”.
We add another button to the dialog:
We can solve the problem of the memory leak, and of the premature destructor call, by simply blocking until the thread is finished:
One simple way to run the task in the background, while reporting progress, which still allows the dialog to be repainted/moved correctly is to busy-wait for the background thread to finish, while pumping messages:
The reason that our previous example consumes 100% CPU is that it busy-waits while pumping messages. The correct answer
is to run the dialog box modally. However, we can’t (easily) use DoModal, because this causes ordering problems. Do we
create the thread or the dialog first?