I have an MFC application whose GUI has a start and a stop button. The start button calls a function which I want to run in the background, periodically. My solution was to use the
SetTimer
function to call the
OnTimer
function at regular intervals. This function then creates a thread using
AfxBeginThread
and then populates the structure that I pass to the thread as a parameter. All this works just fine.
What I would like to do now is the make the stop button end the thread. I have read about
TerminateThread
but it seems too risky. Since I want to close the worker thread from another thread, I know I can't use
AfxEndThread
, but I wanted to know why the following solution doesn't work.
What I have tried:
I created an
int
variable called
count
and set it to
0
whenever start is pressed, and set it to
1
whenever stop is pressed.
The structure I am passing into
AfxBeginThread
looks like this
typedef struct THREADSTRUCT
{
MyGUIDlg* _this;
int flag;
} THREADSTRUCT;
When start is pressed the
SetTimer
function is called, whose callback function is defined like this:
void MyGUIDlg::OnTimer(UINT_PTR nIDEvent)
{
THREADSTRUCT* _param = new THREADSTRUCT;
_param->_this=this;
_param->flag = count;
AfxBeginThread(StartThread, _param);
CDialog::OnTimer(nIDEvent);
}
In my StartThread function I have added the following:
UINT MyGUIDlg::StartThread(LPVOID param)
{
THREADSTRUCT *ts = (THREADSTRUCT*)param;
if((ts->flag)==1)
{
}
return 0;
}
But this doesn't seem to work, any thoughts why?