Wait for thread completion without freezing the UI in MFC

1k views Asked by At

I am trying to start a worker thread using AfxBeginThread and wait until it finished. But I run into the issue, that I can either update the UI (show progress) without the thread conrol or wait for the thread but the UI freezes. I found out several approaches for getting the completion but they all use WaitForSingleObject. Is there any other solution for this? Here is my example code:

UINT CProgressBarSampleDlg::MyControllingFunction(LPVOID pParam)
{
    CProgressBarSampleDlg* pObject = (CProgressBarSampleDlg*)pParam;

    for (size_t i = 0; i < 10; i++)
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(100)); // simulate long running operation
        
        pObject->m_ProgressBar.StepIt(); // update progress
    }
    
    return 0;
}

void CProgressBarSampleDlg::OnBtnStartClicked()
{
    auto thread = AfxBeginThread(MyControllingFunction, this);
    
    // ... this freezes the UI!
    thread->m_bAutoDelete = FALSE;
    WaitForSingleObject(thread->m_hThread, INFINITE);
    delete thread;
}
1

There are 1 answers

0
alex555 On

Well, with Richard's suggestion I solved it this way. Also, the progress bar access was moved into the message handler.

UINT CProgressBarSampleDlg::MyControllingFunction(LPVOID pParam)
{
    CProgressBarSampleDlg* pObject = (CProgressBarSampleDlg*)pParam;

    pObject->SendMessage(WM_THREAD_1, 0, (LPARAM)1);
    for (size_t i = 0; i < 10; i++)
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(100)); // simulate long running operation            
        pObject->SendMessage(WM_THREAD_1, 0, (LPARAM)2);
    }
    
    pObject->SendMessage(WM_THREAD_1, 0, (LPARAM)3);
    return 0;
}


void CProgressBarSampleDlg::OnBtnStartClicked()
{
    AfxBeginThread(MyControllingFunction, this);
}

Thanks for your ideas