Strange behaviour of function Sleep() used in repeat until in Delphi

前端 未结 4 1360
走了就别回头了
走了就别回头了 2021-01-19 01:28

I have function which is reaction on button click. When I click on the button it should start repeat and write values form an array and show them in labels on main form. Pro

4条回答
  •  梦谈多话
    2021-01-19 02:23

    If you must use a delay or "sleep" type function, you can use a procedure with ProcessMessages. There are some plusses and minuses to using it, but I have successfully on many occasions with no ill effects. I know there are others here who can better comment on ProcessMessages.

    Procedure Delay(MSecs: Cardinal);
    var
     FirstTick, CurrentTick : Cardinal;
     Done : Boolean;
    begin
     Done := FALSE;
     FirstTick := GetTickCount;
     While Not Done do
      begin
       Application.ProcessMessages;
       CurrentTick := GetTickCount;
       If Int64(CurrentTick) - Int64(FirstTick) < 0 Then
        begin
         If CurrentTick >= (Int64(FirstTick) - High(Cardinal) + MSecs) Then
          Done := TRUE;
           End
            Else
             If CurrentTick - FirstTick >= MSecs Then
              Done := TRUE;
      end;
    end;
    
    // Below for a service
    
    procedure YourSvrSvc.ProcessMessages;
    var
      Msg: TMsg;
    begin
      if PeekMessage(Msg, 0, 0, 0, PM_REMOVE) then
      begin
        TranslateMessage(Msg);
        DispatchMessage(Msg);
      end;
    end;
    
    Procedure YOURSvrSvc.Delay(MSecs: Cardinal);
    var
     FirstTick, CurrentTick : Cardinal;
     Done : Boolean;
    begin
     Done := FALSE;
     FirstTick := GetTickCount;
     While Not Done do
      begin
       YOURSvrSvc.ProcessMessages;
       CurrentTick := GetTickCount;
       If Int64(CurrentTick) - Int64(FirstTick) < 0 Then
        begin
         If CurrentTick >= (Int64(FirstTick) - High(Cardinal) + MSecs) Then
          Done := TRUE;
           End
            Else
             If CurrentTick - FirstTick >= MSecs Then
              Done := TRUE;
      end;
    end;
    

提交回复
热议问题