MFC thread only runs if caller is waiting in a MessageBox

I am developing an MFC dialog application that interfaces to a device through a provided API. One of the functions within the API enters a polling loop, so to keep my dialog active while the API is polling, I have created a thread to handle all of that, but the thread only runs if the calling dialog is stuck waiting for a MessageBox. This is my first MFC app, so forgive my ignorance with much of this.

I'll try to summarize what I'm doing now:

The main dialog app is contained in this class:
class CTelloSPI6Dlg : public CDialogEx

A public member function in CTelloSPI6Dlg serves as the thread:
static UINT SPI_Comm_Thread(LPVOID pParam);

It's started here:
AfxBeginThread( SPI_Comm_Thread, (LPVOID) &tmpHWND, THREAD_PRIORITY_NORMAL);

This works, except for one thing: The new thread, SPI_Comm_Thread only functions if the calling dialog app is sitting, waiting for the user to click OK on a MessageBox. In other words, when AfxBeginThread starts the thread, nothing will happen with the thread unless a MessageBox is brought up in the calling code. Once the thread is running, if the MessageBox is closed, then SPI_Comm_Thread stops running. It doesn't exit or terminate, it just quits running.

Is this because the dialog app is created as a modal dialog?
Take a look here:
BOOL CTelloSPI6App::InitInstance()
{
...
CTelloSPI6Dlg dlg;
m_pMainWnd = &dlg;
INT_PTR nResponse = dlg.DoModal();

Is it possible to change it to a modeless dialog without recreating everything?

I have tried changing the priority of SPI_Comm_Thread, but that doesn't change anything.

Thanks!!!
Last edited on
> AfxBeginThread( SPI_Comm_Thread, (LPVOID) &tmpHWND, THREAD_PRIORITY_NORMAL);
What exactly is tmpHWND?
How does SPI_Comm_Thread use it?

If it's a local variable, or a non-static class member variable, then as soon as your dialog exits, the pointer that SPI_Comm_Thread sees is pointing to illegal memory and promptly dies.

You need to ensure that the lifetime of your thread parameter is at least as long as the thread itself.

Also here -> http://forums.codeguru.com/showthread.php?563845-MFC-Dialog-app-thread-doesn-t-run-unless-caller-is-stuck-wiating-for-MessageBox
Last edited on
Salem,
You got it!!!! The calling object handle tmpHWND was a local variable. The MessageBox was serving to keep the calling function from exiting and kept tmpHWND valid. I changed tmpHWND to be class member and now it's working nicely! Since this is a dialog application, the dialog is active for the duration of the application.
Thanks so much!!!
Last edited on
Registered users can post here. Sign in or register to post.