阻塞延时与非阻塞延时的实现--上位机VC
阻塞延时与非阻塞延时的实现--上位机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);
- }
复制代码我们来演示下功能实现的整个过程
如果您认可,可联系功能定制! 如果您着急,充值会员可直接联系发您资料!
|