求个MFC中sleep延时不阻塞(程序未响应)的方法
本帖最后由 Himajesty 于 2013-10-24 21:47:00 编辑 有个不是窗口的类 有函数A 函数B 要求执行 A之后 延时指定时间 之后再 执行B
A();
Sleep(5000);
B(); // 这个函数也可能是其他函数
代码这样写的话 在sleep的时候 程序会造成未响应 状态 求指导怎么替换sleep() 这个函数要求 执行完 A()之后 代码延时一定时间后(延时期间 程序不能未响应)继续执行后面的代码 意思就是代码延时 而不是程序延时 求代码 谢谢了 mfc 延时 阻塞
[解决办法]
多线程,Sleep(5000);写在A()之内.
建立状态变量int x=0;
A()
{
while(x!=2);
//做爱 做的事
Sleep(5000);
x--;
}
B()
{
while(x!=1);
//做爱 做的事
x--;
}
主程序()
{
启动线程A;
启动现成B;
x=2; //开始执行
}
[解决办法]
VOIDNSys::IdleSleep(DWORD dwTime, HWND hWnd = NULL)
{
MSGmsg;
DWORDTstart, Time;
BOOLbRetVal;
inti;
Tstart = GetTickCount();
for(i=0; ; i++)
{
bRetVal = PeekMessage(&msg, hWnd, NULL, NULL, PM_REMOVE);
if(bRetVal)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
if(hWnd)
{
if(msg.message == WM_CLOSE
[解决办法]
msg.message == WM_COMMAND && (msg.wParam == IDOK
[解决办法]
msg.wParam == IDCANCEL))
return;
}
if(i<100)
continue;
}
Time = GetTickCount();
if(Time - Tstart >= dwTime)
return;
Sleep(1);
}
}
根据需要自己可以简化
[解决办法]
给你吧。。。XSLEEP函数,不知道谁写的。。。我自己用下来有用。。
XSLEEP.CPP
//Download by http://www.NewXing.com
#include <windows.h>
// This structure is used internally by the XSleep function
struct XSleep_Structure
{
int duration;
HANDLE eventHandle;
};
//////////////////////////////////////////////////////////////////////
// Function : XSleepThread()
// Purpose : The thread which will sleep for the given duration
// Returns : DWORD WINAPI
// Parameters:
// 1. pWaitTime -
//////////////////////////////////////////////////////////////////////
DWORD WINAPI XSleepThread(LPVOID pWaitTime)
{
XSleep_Structure *sleep = (XSleep_Structure *)pWaitTime;
Sleep(sleep->duration);
SetEvent(sleep->eventHandle);
return 0;
}
//////////////////////////////////////////////////////////////////////
// Function : XSleep()
// Purpose : To make the application sleep for the specified time
// duration.
// Duration the entire time duration XSleep sleeps, it
// keeps processing the message pump, to ensure that all
// messages are posted and that the calling thread does
// not appear to block all threads!
// Returns : none
// Parameters:
// 1. nWaitInMSecs - Duration to sleep specified in miliseconds.
//////////////////////////////////////////////////////////////////////
void XSleep(int nWaitInMSecs)
{
XSleep_Structure sleep;
sleep.duration = nWaitInMSecs;
sleep.eventHandle = CreateEvent(NULL, TRUE, FALSE, NULL);
DWORD threadId;
CreateThread(NULL, 0, &XSleepThread, &sleep, 0, &threadId);
MSG msg;
while(::WaitForSingleObject(sleep.eventHandle, 0) == WAIT_TIMEOUT)
{
//get and dispatch messages
if(::PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
}
CloseHandle(sleep.eventHandle);
}
xsleep.h
//Download by http://www.NewXing.com
#ifndef _XSLEEP_H_
#define _XSLEEP_H_
void XSleep(int nWaitInMSecs);
#endif // _XSLEEP_H_