Using background threads for long processes in MFC
...
...
Essentially, this gives us a task that we can run. It demonstrates two things — the longevity of the task, and the fact that it reports its progress reasonably infrequently.
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?