class IThreadFun
{
public:
virtual void OnDo()=0;
};
//每200毫秒调用一次IThreadFun的OnDo
class CThreadHlp
{
public:
static void StartThread(IThreadFun* pFun)
{
if( NULL != s_pThread )
return ;
s_pFun = pFun ;
s_bDo = true;
s_pThread = AfxBeginThread(SysThreadFun,NULL);
}
static void EndThread()
{
if( NULL == s_pThread )
return ;
s_bDo = false;
WaitForSingleObject(s_pThread->m_hThread, INFINITE);//
s_pThread = NULL;
}
protected:
static IThreadFun* s_pFun;
static bool s_bDo ;
static CWinThread* s_pThread;
static UINT SysThreadFun(LPVOID p)
{
while(s_bDo )
{
Sleep(200);//可优化
if( NULL != s_pFun )
{
s_pFun->OnDo();
}
}
return 0;
}
};
//
IThreadFun* CThreadHlp::s_pFun = NULL ;
bool CThreadHlp::s_bDo = false ;
CWinThread* CThreadHlp::s_pThread = NULL;
class CTestThreadFun : public IThreadFun
{
public:
virtual void OnDo()
{
for( int i = 0 ; i < 10 ; i++ )
{
CString str;
str.Format("%d ",i);
TRACE(str);
Sleep(100);
}
TRACE("\r\n");
}
};
测试环境:Win7+VS2005
CTestThreadFun fun;
CThreadHlp hlp ;
void CtestexeDlg::OnBnClickedButton2()
{
hlp.StartThread(&fun);
}
void CtestexeDlg::OnBnClickedButton3()
{
hlp.EndThread();
}
无论如何点击 Btn2和Btn3,输出都是完整的(1到10都有)
单击Btn2后直接关闭,输出可能不完整。