PostMessage from WorkerThread to Main Window in MFC

拈花ヽ惹草 提交于 2019-11-28 03:53:03

问题


I have a MFC application, which has a worker thread, what I want to do is to post message from worker thread to the Main GUI thread to update some status messages on GUI. What I have done so far is Registered a new window message

//custom messages
static UINT FTP_APP_STATUS_UPDATE = ::RegisterWindowMessageA("FTP_APP_STATUS_UPDATE");

Added this message to the message map of dialog class

ON_MESSAGE(FTP_APP_STATUS_UPDATE, &CMFC_TestApplicationDlg::OnStatusUpdate)

The prototype of OnStatusUpdate is

afx_msg LRESULT OnStatusUpdate(WPARAM, LPARAM);

and definition is

LRESULT CMFC_TestApplicationDlg::OnStatusUpdate(WPARAM wParam, LPARAM lParam)
{

     //This function is not called at all.
     return 0;
}

and the worker thread calling code is

void CMFC_TestApplicationDlg::OnBnClickedMfcbutton1()
{
    ThreadParams params;
    params.m_hWnd = m_hWnd;
    params.FTPHost = "test_host";
    params.FTPUsername = "test";
    params.FTPPassword = "test";

    AfxBeginThread(FTPConnectThread,&params);
}

and Worker thread code is

//child thread function
UINT FTPConnectThread( LPVOID pParam )
{
    if(pParam == NULL)
    {
        return 0;
    }
    ThreadParams *params = (ThreadParams*)pParam;
    OutputDebugString(params->FTPHost);
    Sleep(4000); //simulating a network call
    CString * message = new CString("Conencted");
    PostMessage(params->m_hWnd,FTP_APP_STATUS_UPDATE,0,(LPARAM)message);
    //PostMessage do nothing? what I am doing wrong?
    return 1;
}

the problem is when the PostMessage function is called the OnStatusUpdate should be called, but it is not being called, no exception or assertion is thrown, What I am doing wrong? I have tried ON_REGISTERED_MESSAGE and ON_MESSAGE but no success, any help?


回答1:


CMFC_TestApplicationDlg::OnBnClickedMfcbutton1() may return before the thread starts. This causes your ThreadParams to go out of scope, so when you access it from the thread, you are accessing freed memory. You need to allocate it some other way, such as:

void CMFC_TestApplicationDlg::OnBnClickedMfcbutton1()
{
    ThreadParams* params = new ThreadParams();
    params->m_hWnd = m_hWnd;
    params->FTPHost = "test_host";
    params->FTPUsername = "test";
    params->FTPPassword = "test";

    AfxBeginThread(FTPConnectThread,params);
}

//child thread function
UINT FTPConnectThread( LPVOID pParam )
{
    if(pParam == NULL)
    {
        return 0;
    }

    ThreadParams *params = (ThreadParams*)pParam;
    OutputDebugString(params->FTPHost);
    Sleep(4000); //simulating a network call
    CString * message = new CString("Conencted");
    PostMessage(params->m_hWnd,FTP_APP_STATUS_UPDATE,0,(LPARAM)message);

    delete params;
    return 1;
}


来源:https://stackoverflow.com/questions/10719902/postmessage-from-workerthread-to-main-window-in-mfc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!