MFC中工作线程的使用

Usage of worker threads in MFC

本文关键字:线程 工作 MFC      更新时间:2023-10-16
//Case I : ( It works but not sure if it is safe . Is it because the windows
             messages are handle in a process queue already? )
void MyDlg::OnClickButton1()
{
     std::thread([]()
     {
          // some long computation here
         SetDlgItemText(IDC_STATIC_TEXT, L"Updated");
     }).detach();
}

//Case II : ( It works . But is the process_queue redundant ) 
void MyDlg::OnClickButton1()
{
     std::thread([]()
     {
          // some long computation here
         command_node node =   
         command_factory("SetDlgItemText",IDC_STATIC_TEXT, "Updated");
         SendMessageToMyProcessQueue(node);         
     }).detach();
}
void MyDlg::OnPaint()
{
       ExecuteFromMyProcessQueue();
       CDialogEx::OnPaint();
}

这是一个使用MFC的vc++示例片段,我想使用一个工作线程来完成任务并将结果发送到控件。哪一个是理想的或者其他的工作?

避免从主线程以外的其他线程直接访问GUI通常是一个好主意(或必要的)。MFC可能断言,也可能不断言,这取决于它实现的一致性。参见这个答案。这就排除了你的第一种情况。

使用消息队列是安全且正确的方法。关于如何从另一个线程更新UI,请参见此线程