从线程MFC发送返回值到对话框

时间:2013-10-08 15:59:57

标签: c++ multithreading mfc

我正在使用do modal创建对话框:

MainHamsterDlg MainHamsterDlg;
 if (MainHamsterDlg.DoModal() == IDCANCEL)
 break;

然后在该对话框中创建工作线程:

BOOL MainHamsterDlg::OnInitDialog()
    {
        AfxBeginThread(WorkerThreadProc, m_hWnd, THREAD_PRIORITY_NORMAL, 0, 0, NULL);
        CDialogEx::OnInitDialog();

        return TRUE;
    }

线程必须通过发送返回值IDCANCEL退出对话框。

    UINT WorkerThreadProc(LPVOID Param) //Sample function for using in AfxBeginThread
    {
        Sleep(1000); // process simulation
        MainHamsterDlg * self = (MainHamsterDlg *)Param;
        self->EndDialog(IDCANCEL);
        return FALSE;
    }

编译时我没有收到任何错误。当处理然后得到点:

self->EndDialog(IDCANCEL);

错误消息:

Unhandled exception at 0x01503AD4 in L2Hamster.exe: 0xC0000005:
Access violation reading location 0x00000020.

指向我的dlgcore.cpp文件:

void CDialog::EndDialog(int nResult)
{
    ASSERT(::IsWindow(m_hWnd)); <<<<<===== to that line

    m_bClosedByEndDialog = TRUE;

    if (m_nFlags & (WF_MODALLOOP|WF_CONTINUEMODAL))
        EndModalLoop(nResult);

    ::EndDialog(m_hWnd, nResult);
}

我不知道我做错了什么。任何解决方案?

2 个答案:

答案 0 :(得分:2)

这看起来对我来说是个问题:

AfxBeginThread(WorkerThreadProc, NULL, THREAD_PRIORITY_NORMAL, 0, 0, NULL);

接着是

UINT WorkerThreadProc(LPVOID Param) //Sample function for using in AfxBeginThread
{
    MainHamsterDlg * self = (MainHamsterDlg *)Param;
        self->EndDialog(IDCANCEL);
    ...
}

此处ParamNULL,因此selfNULL。然后取消引用空指针。

答案 1 :(得分:2)

我假设您打算将指向对话框的指针传递给线程proc。但你改为传递null:

 AfxBeginThread(WorkerThreadProc, NULL, THREAD_PRIORITY_NORMAL, 0, 0, NULL);

应该是:

 AfxBeginThread(WorkerThreadProc, this, THREAD_PRIORITY_NORMAL, 0, 0, NULL);

您还需要将线程的结尾与对话框的结尾进行协调,以确保在线程结束之前不会关闭对话框。 (我假设它是某种进度对话框)。