【问题标题】:Usage of worker threads in MFCMFC 中工作线程的使用
【发布时间】:2016-08-26 06:49:14
【问题描述】:
//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++ 中的示例 sn-p,我想使用工作线程来完成任务并将结果发送到控件。哪个是可取的或任何其他解决方法?

【问题讨论】:

  • 不重复。较早的线程只关注案例 I,建议禁止在 MFC GUI 线程中使用工作线程。我的查询案例 II 尝试通过使用异步优先级队列并允许主 GUI 线程处理发布消息来探索解决该情况的方法

标签: c++ multithreading visual-c++


【解决方案1】:

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

使用消息队列是安全且正确的方法。另请参阅this thread,了解如何从另一个线程更新 UI。

【讨论】:

    猜你喜欢
    • 2011-10-27
    • 2014-02-02
    • 2014-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多