等待函數(保持界面正常響應)

取自網絡


//延時函數,msec 爲毫秒

procedure Delay(msec: single);
var
  FirstTickCount: real;
begin
  if msec > 0 then
  begin
    FirstTickCount := GetTickCount();
    FirstTickCount := FirstTickCount + msec;
    while FirstTickCount > GetTickCount() do
      Application.HandleMessage; //關鍵在這裏
  end;
end;


// 測試CPU佔用率<1% (CPU i3)


// 等待函數(保持界面正常響應) MSecs爲毫秒
procedure WaitTime(MSecs: Integer);
var
  FirstTickCount, Now: Longint;
begin
  FirstTickCount := Windows.GetTickCount();
  repeat
    Now := Windows.GetTickCount();
    Application.ProcessMessages;
  until (Now - FirstTickCount >= MSecs) or (Now < FirstTickCount);
end;

// 測試CPU佔用率10% -- 25%  (CPU i3)


// *通過測試,在線程中調用Delay函數,存在線程函數執行中斷(不在有任何響應,但主程序仍正常執行)的情況,而調用WaitTime則正常

// 爲降低CPU佔用率將WaitTime函數代碼修改如下:

// 等待函數(保持界面正常響應) MSecs爲毫秒
procedure WaitTime(MSecs: Integer);
var
  FirstTickCount, Now: Longint;
begin
  FirstTickCount := Winapi.Windows.GetTickCount();
  repeat
    Sleep(1);  // 避免CPU佔用率高
    Application.ProcessMessages;
    Now := Winapi.Windows.GetTickCount();
  until (Now - FirstTickCount >= MSecs) or (Now < FirstTickCount);
end;

// 測試CPU佔用率 < 1%  (CPU i3)


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章