Re: MFC and threads
On Wed, 04 Apr 2007 11:57:22 -0400, Joseph M. Newcomer
<newcomer@flounder.com> wrote:
There are a couple solutions to this problem.
The choices depend on some performance issues. The simplest one is the following:
typedef struct {
HANDLE event;
UINT result;
} QueryParameters;
UINT CMyThread::Query()
{
QueryParameters parms;
parms.event = ::CreateEvent(NULL, TRUE, FALSE, NULL);
target->PostMessage(UWM_QUERY_WHATEVER, (WPARAM)&parms);
::WaitForSingleObject(parms.event, INFINITE);
::CloseHandle(parms.event);
return parms.result;
}
ON_[REGISTERED_]MESSAGE(UWM_QUERY_WHATEVER, OnQueryWhatever)
LRESULT CMyWindow::OnQueryWhatever(WPARAM wParam, LPARAM)
{
QueryParameters * parms = (QueryParameters *)wParam;
CQueryDialog dlg;
parms->result = dlg.DoModal();
::SetEvent(parms->event);
return 0;
}
Note this does something a little strange: it passes the address of a local variable
across a thread boundary. This is normally an erroneous action, but because of the
::WaitForSingleObject, the thread is suspended so the stack address remains valid. (This
is a paradigm used in device drivers for PnP event handling).
Error detection on the WFSO is left as an Exercise For The Reader.
joe
I'd submit this is even simpler:
UINT CMyThread::Query()
{
return (UINT) target->SendMessage(UWM_QUERY_WHATEVER);
}
ON_[REGISTERED_]MESSAGE(UWM_QUERY_WHATEVER, OnQueryWhatever)
LRESULT CMyWindow::OnQueryWhatever(WPARAM, LPARAM)
{
return dlg.DoModal();
}
--
Doug Harrison
Visual C++ MVP