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

15 Apr 2003 11:54 mfc

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?

However, MFC comes to our rescue with RunModalLoop:

void CBgthreadDlg::OnBackgroundModal()
    CProgressDlg dlg;

    TaskThread *t = new TaskThread(&dlg);


    delete t;


The only complication with this is that RunModalLoop doesn’t return until the dialog calls EndDialog. In order to cope with this, we have to add an OnComplete method to the observer, so that the dialog knows when the process is complete.

The source code: