7

我有一个 MFC 应用程序,它有一个工作线程,我想做的是从工作线程向主 GUI 线程发布消息,以更新 GUI 上的一些状态消息。到目前为止我所做的是Registered a new window message

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

将此消息添加到对话框类的消息映射中

ON_MESSAGE(FTP_APP_STATUS_UPDATE, &CMFC_TestApplicationDlg::OnStatusUpdate)

的原型OnStatusUpdate

afx_msg LRESULT OnStatusUpdate(WPARAM, LPARAM);

定义是

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

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

并且工作线程调用代码是

void CMFC_TestApplicationDlg::OnBnClickedMfcbutton1()
{
    ThreadParams params;
    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);
    //PostMessage do nothing? what I am doing wrong?
    return 1;
}

问题是当 PostMessage 函数被调用时OnStatusUpdate应该被调用,但它没有被调用,没有异常或断言被抛出,我做错了什么?我试过了ON_REGISTERED_MESSAGEON_MESSAGE但没有成功,有什么帮助吗?

4

1 回答 1

5

CMFC_TestApplicationDlg::OnBnClickedMfcbutton1()可能在线程开始之前返回。这会导致您ThreadParams超出范围,因此当您从线程访问它时,您正在访问已释放的内存。您需要以其他方式分配它,例如:

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;
}
于 2012-05-23T12:34:37.940 回答