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();
}