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后直接关闭,输出可能不完整。

posted on   闻缺陷则喜何志丹  阅读(7)  评论(0编辑  收藏  举报  
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~



点击右上角即可分享
微信分享提示