WaitForSingleObject returns wait failed due to inv

2019-06-06 03:35发布

问题:

I am trying to use a CEvent to make my thread wait until the message queue is ready as per MSDN's advice so that my PostThreadMessage function will work correctly.

BOOL MFC_Thread::InitInstance(){
BOOL worked=CWinThread::InitInstance();
MSG msg;
BOOL result=PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
    fingerveinControllerThreadReady->SetEvent();//Breakpoint 1
    return TRUE;
}

void init(){
    controllerThreadReady=new CEvent(FALSE, FALSE);
CWinThread* thread=AfxBeginThread(RUNTIME_CLASS(MFC_Thread));
controllerThread=thread->m_nThreadID;
WaitForSingleObject(controllerThreadReady, INFINITE);
    DoSomething();//Breakpoint 2
}

Unfortunately, it seems that the WaitForSingleObject isn't doing its job. Sometimes Breakpoint 1 is hit first, sometimes Breakpoint 2. When Breakpoint 2 is hit first, I receive WAIT_FAILED with the cause ERROR_INVALID_HANDLE. Why is this happening?

回答1:

That might be because you're passing the CEvent object instead of its handle.

Try this:

WaitForSingleObject(controllerThreadReady.m_hObject, INFINITE);



标签: mfc