[英]Wait for thread completion without freezing the UI in MFC
I am trying to start a worker thread using AfxBeginThread
and wait until it finished.我正在尝试使用
AfxBeginThread
启动一个工作线程并等待它完成。 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.但是我遇到了一个问题,我可以在没有线程控制的情况下更新 UI(显示进度),或者等待线程但 UI 冻结。 I found out several approaches for getting the completion but they all use
WaitForSingleObject
.我发现了几种获得完成的方法,但它们都使用
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;
}
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谢谢你的想法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.