工控编程吧
标题:
阻塞延时与非阻塞延时的实现--上位机VC
[打印本页]
作者:
qq263946146
时间:
2016-11-30 20:00
标题:
阻塞延时与非阻塞延时的实现--上位机VC
(, 下载次数: 0)
上传
点击文件名下载附件
阻塞延时与非阻塞延时的实现--上位机VC
功能展示
用过函数sleep()的都知道,使用此函数程序界面会出现不反的应假死现象,用户体验不够友好,当前例程实现sleep的扩展,延时界面仍旧可以操作,效果如图。点击<阻塞延时3S>程序调用sleep()函数,期间界面不可操作,点击<非阻塞延时3s>期间程序界面可任意操作
要点提示
非阻塞延时函数功能主要是通过线程实现,在线程中实现消息的再分配及开辟另一线程调用Sleep()函数,直到延时到位退出两线程;
实现功能
1.新建基于对话框的应用程序
2.拖拽一列表框控件,ID保持不变,添加按钮<阻塞延时3S><非阻塞延时3S>实现两种延时功能
void CGkbc8Dlg::OnButton1() //阻塞延时
{
time_t startTime = time(NULL);
Sleep(3000);
time_t endTime = time(NULL);
CString sText;
sText.Format("block slept for %.0f ms",difftime(endTime, startTime));
CListBox *pList = (CListBox*)GetDlgItem(IDC_LIST1);
pList->InsertString(0,sText);
}
void CGkbc8Dlg::OnButton2() //非阻塞延时
{
DWORD threadId;
CreateThread(NULL, 0, TestSleepTheadFunc, this, 0, &threadId);
/*
time_t startTime = time(NULL);
XSleep(3000); // THIS IS THE MAIN FUNCTION CAL
time_t endTime = time(NULL);
CString sText;
sText.Format("not block slept for %.0f ms",difftime(endTime, startTime));
CListBox *pList = (CListBox*)GetDlgItem(IDC_LIST1);
pList->InsertString(0,sText);
*/
}
复制代码
3.再实现线程函数TestSleepTheadFunc及Xsleep()函数
DWORD WINAPI TestSleepTheadFunc(LPVOID param)
{
time_t startTime = time(NULL);
XSleep(3000); // THIS IS THE MAIN FUNCTION CAL
time_t endTime = time(NULL);
CString sText;
sText.Format("not block slept for %.0f ms",difftime(endTime, startTime));
CGkbc8Dlg* pDlg = (CGkbc8Dlg*)param;
复制代码
ListBox *pList = (CListBox*)pDlg->GetDlgItem(IDC_LIST1);
pList->InsertString(0,sText);
return 0;
}
struct XSleep_Structure
{
int duration;
HANDLE eventHandle;
};
DWORD WINAPI XSleepThread(LPVOID pWaitTime)
{
XSleep_Structure *sleep = (XSleep_Structure *)pWaitTime;
Sleep(sleep->duration);
SetEvent(sleep->eventHandle);
return 0;
}
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)
{
if(::PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))//get and dispatch messages
{
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
}
CloseHandle(sleep.eventHandle);
}
复制代码
我们来演示下功能实现的整个过程
[iqiyi]http://player.video.qiyi.com/df0cd8fb9d924fbf75cb88e8a5e8df25/0/0/w_19ruj9bzpl.swf-albumId=6859495909-tvId=6859495909-isPurchase=0-cnId=12[/iqiyi]
(, 下载次数: 0)
上传
点击文件名下载附件
[weixinlianxi]1[/weixinlianxi]
欢迎光临 工控编程吧 (https://www.gkbc8.com/)
Powered by Discuz! X3.4