我正在尝试使用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;
}