1

我正在尝试使用AfxBeginThread并等待它完成来启动一个工作线程。但是我遇到了一个问题,我可以在没有线程控制的情况下更新 UI(显示进度),或者等待线程但 UI 冻结。我发现了几种获得完成的方法,但它们都使用WaitForSingleObject. 有没有其他解决方案?这是我的示例代码:

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;
}
4

1 回答 1

0

好吧,根据理查德的建议,我以这种方式解决了它。此外,进度条访问已移至消息处理程序中。

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);
}

谢谢你的想法

于 2020-08-13T13:13:12.137 回答