下面这个程序是创建线程的地方,点击开始 按钮 就开始执行。当点击 暂停 按钮就挂起线程,再点击一次 恢复 线程。
void CCDlg::OnBUTTONStart() 
{
// TODO: Add your control notification handler code here
UpdateData(TRUE);
FILE * myfile2;
int allintest=m_list_intest.GetItemCount();  
if (allintest==0)
{
MessageBox("待测项目数为零,请先添加测试项目","警告",MB_OK);
return;
} /*子线程部分*/
DISPARAM *pDisplayParam=new DISPARAM;
pDisplayParam->totalcnt=m_edit_totalcnt;
pDisplayParam->hwnd=m_hWnd;//句柄传递,所有的与窗口有关的类,都有一个数据成员m_hWnd,
                           //m_hWnd保存了和这个类相关的窗口句柄
hThread=CreateThread(NULL,0,DisProc,(LPVOID)pDisplayParam,0,NULL);//创建线程
CloseHandle(hThread);//递减线程内核对象的使用计数 GetDlgItem(IDC_BUTTON_Start)->EnableWindow(FALSE); 
GetDlgItem(IDC_BUTTON_Setup)->EnableWindow(FALSE);  
myfile2=fopen(filepath,"a"); //文件存在,就增加但不覆盖原内容
char temp[100];
sprintf(temp,"总共测试次数:%d\n",m_edit_totalcnt);
fwrite(temp,strlen(temp),1,myfile2);
fclose(myfile2);
GetDlgItem(IDC_BUTTON_Pause)->EnableWindow(TRUE); //按钮变灰
GetDlgItem(IDC_BUTTON_Stop)->EnableWindow(TRUE); 
GetDlgItem(IDC_BUTTON_Save)->EnableWindow(FALSE); 
GetDlgItem(IDC_BUTTON_Load)->EnableWindow(FALSE); 
UpdateData(FALSE);
}DWORD WINAPI CCDlg::DisProc(LPVOID lpParameter)
{
int totalcnt=((DISPARAM*)lpParameter)->totalcnt;
int current;
HWND hwnd=((DISPARAM*)lpParameter)->hwnd;
delete lpParameter; //释放内存
for (int i=1;i<totalcnt+1;i++)
{
current=i;
::PostMessage(hwnd,WM_DISDATA,0,(LPARAM)current);//调用消息
Sleep(1000);
}
return 0;
}这个地方暂停,恢复线程的运行,void CCDlg::OnBUTTONPause() 
{
// TODO: Add your control notification handler code here
m_static_pass="暂停";
PauseFlag=!PauseFlag;
Sleep(1);
if (PauseFlag==0)//pubic 变量,用于 判断线程的 挂起,恢复
{
SuspendThread(hThread);
Sleep(1);

else
{
ResumeThread(hThread);
Sleep(1);
}
}我编译通过了,运行无错误, 现在就是点击了 暂停 的时候,线程 不挂起,请问为什么?
谢谢了。

解决方案 »

  1.   

    如果我没看错的话:CloseHandle(hThread);这句话已经关闭了进程句柄,对其后续调用(包括挂起进程)都无效。所以去掉上面那行试试
      

  2.   

    确实是这样的
    hThread=CreateThread(NULL,0,DisProc,(LPVOID)pDisplayParam,0,NULL);//创建线程
    CloseHandle(hThread);//递减线程内核对象的使用计数
    这部分代码是对着 孙鑫老师的代码写的, 没搞懂, 汗、、、谢谢了, 哈哈、、、