Using background threads for long processes in MFC: Background Thread 3

15 Apr 2003 11:53 mfc

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:

void CBgthreadDlg::OnBackgroundBusy()
    CProgressDlg dlg;

    TaskThread *t = new TaskThread(&dlg);

    // Wait for it to finish, but pump messages in the meantime.
    while (t->GetExitStatus() == STILL_ACTIVE)

    delete t;


This works fine, but for the problem that it uses 100% CPU while busy-waiting. This wastes CPU power, because it has to keep context-switching, and it’ll ruin battery life on a laptop, because the CPU is running continuously.