Wait procedure
Return to Introduction  Previous page  Next page
Unit
acUtils  

Declaration
procedure Wait(var WaitHandle: THandle; Timeout: DWord = 0);  

Description
The Wait procedure used to wait some time in that line of code which called Wait procedure, until the WaitHandle (system event) is signalled (StopWait procedure is called), OR the Timeout is expired. After calling the StopWait procedure, or expiration of the Timeout, the program will continue from the next line of your code.  
 
tip The Wait and StopWait routines should be used instead "while something do Application.ProcessMessages;", to not utilize CPU time for long time, until some operation will be completed.  
 
Remarks
When Timeout parameter is set to 0, the function considering it as Timeout does not specified, so procedure will wait infinitely, until the WaitHandle is signalled (or StopWait procedure will be called).  

Example
TMyForm = class(TForm)  
private  
  FWaitEvent: THandle;  
public  
  procedure CallSomethingAndWait;  
  procedure DestroySomethingAndStopWait(Sender: TObject);  
end;  
 
procedure TMyForm.CallSomethingAndWait;  
begin  
  // ...call something  
 
  Wait(FWaitEvent); // ...and wait result...  
 
  // next line will be executed after StopWait will be called OR the application will be terminated  
end;  
 
procedure TMyForm.DestroySomethingAndStopWait(Sender: TObject);  
begin  
  // this code should be executed when the some long operation completed and the program should stop awaiting  
  StopWait(FWaitEvent);  
end;  

Original code
procedure Wait(var WaitHandle: THandle; Timeout: DWord {$IFDEF D4} = 0 {$ENDIF});  
begin  
  if Timeout = 0 then Timeout := INFINITE;  
  WaitHandle := CreateEvent(nil, True, False, nil);  // manual reset, start non-signaled  
  try  
    while not Application.Terminated and  
      (MsgWaitForMultipleObjects(1, WaitHandle, False, Timeout, QS_ALLINPUT) = WAIT_OBJECT_0 + 1do  
     Application.ProcessMessages;  
  finally  
    CloseHandle(WaitHandle);  
    WaitHandle := INVALID_HANDLE_VALUE;  
  end;  
end;  

See also
StopWait procedure.