德尔福:没有冻结和处理消息的睡眠

del*_*les 5 windows delphi delphi-7 delphi-2007

我需要一种暂停函数执行几秒钟的方法.我知道我可以使用sleep方法来执行此操作,但此方法会在执行时"冻结"应用程序.我也知道我可以使用类似下面的代码来避免冻结:

// sleeps for 5 seconds without freezing 
for i := 1 to 5 do
    begin
    sleep(1000);
    application.processmessages;
    end;
Run Code Online (Sandbox Code Playgroud)

这种方法存在两个问题:一个是冻结仍然每一秒发生一次,第二个问题是每秒调用'application.processmessages'.我的应用程序是CPU密集型的,每个进程消息调用做了很多不必要的工作,使用不必要的CPU功率; 我只想暂停工作流程,仅此而已.

我真正需要的是像TTimer一样暂停执行的方法,在下面的例子中:

   // sleeps for 5 seconds
   mytimer.interval := 5000;
   mytimer.enabled := true;
   // wait the timer executes
   // then continue the flow
   // running myfunction
   myfunction;
Run Code Online (Sandbox Code Playgroud)

这种方法的问题是'myfunction'不会等待mytimer,它会在mytimer启用后立即运行.

是否有其他方法可以实现我想要的停顿?

提前致谢.

Rem*_*eau 14

正如David所说,最好的选择是将工作转移到一个单独的线程中,并完全阻止主线程.但是,如果你必须阻止主线程,那么至少你应该只ProcessMessages()在确实有消息等待处理时调用,并让线程在剩下的时间内休眠.您可以使用它MsgWaitForMultipleObjects()来处理,例如:

var
  Start, Elapsed: DWORD;

// sleep for 5 seconds without freezing 
Start := GetTickCount;
Elapsed := 0;
repeat
  // (WAIT_OBJECT_0+nCount) is returned when a message is in the queue.
  // WAIT_TIMEOUT is returned when the timeout elapses.
  if MsgWaitForMultipleObjects(0, Pointer(nil)^, FALSE, 5000-Elapsed, QS_ALLINPUT) <> WAIT_OBJECT_0 then Break;
  Application.ProcessMessages;
  Elapsed := GetTickCount - Start;
until Elapsed >= 5000;
Run Code Online (Sandbox Code Playgroud)

或者:

var
  Ret: DWORD;
  WaitTime: TLargeInteger;
  Timer: THandle;

// sleep for 5 seconds without freezing 
Timer := CreateWaitableTimer(nil, TRUE, nil);
WaitTime := -50000000; // 5 seconds
SetWaitableTimer(Timer, WaitTime, 0, nil, nil, FALSE);
repeat
  // (WAIT_OBJECT_0+0) is returned when the timer is signaled.
  // (WAIT_OBJECT_0+1) is returned when a message is in the queue.
  Ret := MsgWaitForMultipleObjects(1, Timer, FALSE, INFINITE, QS_ALLINPUT);
  if Ret <> (WAIT_OBJECT_0+1) then Break;
  Application.ProcessMessages;
until False;
if Ret <> WAIT_OBJECT_0 then
  CancelWaitableTimer(Timer);
CloseHandle(Timer);
Run Code Online (Sandbox Code Playgroud)


Dav*_*nan 8

将需要暂停的任务移动到单独的线程中,以便它不会干扰UI.

  • 在UI线程中调用Sleep,你将杀死UI.因此,不要在UI线程中调用Sleep.如果你想打电话给Sleep,请在另一个帖子中进行.至于如何以最佳方式解决您的实际问题,我们无法完全看到这个问题. (2认同)