Events for Threads

Click here to change the theme.

The documentation of the CEvent is not as clear as it could be. The following is an outline for one possible use of it. This example could be used in a class that creates a thread, such as a worker thread created by AfxBeginThread, to signal it is time for the thread to complete

In the class, create a pointer to an event item and to a thread and declare the thread procedure:

CEvent *m_pEvent;
CWinThread *m_pThread;
static UINT ThreadProc(CFileMonitorApp *);

In the constructor, initialize them:

m_pEvent = NULL;
m_pThread = NULL;

Then create the event item and the thread:

m_pEvent = new CEvent;
if (!m_pEvent)
    return false;
m_pEvent->ResetEvent();        // Not necessary?
m_pThread = AfxBeginThread((AFX_THREADPROC)ThreadProc, (LPVOID)this);
if (!m_pThread)
    return false;

The thread then waits for it to happen. You might need to specify a time-out interval shorter than INFINITE. Alternatively, you can use a time-out interval of zero and periodically check to see if it is time: It is usually important to check the WaitForSingleObject Return Value.

UINT CEventApp::ThreadProc(CFileMonitorApp *pApp) {
	DWORD ReturnValue;
ReturnValue = WaitForSingleObject(pApp->m_pEvent->m_hObject, INFINITE);
return 0;

When it is time for the thread to end:

ReturnValue = WaitForSingleObject(m_pThread->m_hThread, INFINITE);
delete m_pEvent;

Hosted by