How to stop a Thread for a certain time, without using a Timer?

Posted on

Question :


Next, I have a TThread running parallel to Main Thread . And I have a routine to give a fade in the image. Well, the important thing is that I do this fade in a certain time in milliseconds, so I did the routine based on a TTimer .


When I run the fade command, because of the timer my thread follows the fade independent execution in> to have or not closed. However, what prevents me from giving two or more sequential fades .

So what I need is a way to leave the thread waiting for my command to finish.

I thought of using a simple loop to run fade , but how could I measure time without the timer ? Anyone have any ideas?


Answer :

You can use GetTickCount to return a cardinal number containing the time in milliseconds since the system is turned on. Then when you call again, just check the difference.

Two important points:

1 – When the system stays on for 49.7 days, the cardinal restarts.

2 – When the computer hibernates, the value is also stored.

Then you only implement a function:

function VerificarTimeOut(const TickCountInicial, TempoEsperado: Cardinal): Boolean
  TickCountAtual: Cardinal;
  TickCountAtual := GetTickCount;
  if TickCountInicial <= TickCountAtual then
    Result := (TickCountAtual - TickCountInicial) >= TempoEsperado
    Result := ((MAXCARDINAL - TickCountInicial) + TickCountAtual) >= TempoEsperado;

Then in the thread you do:

procedure EsperaAte(const TempoEspera: Cardinal);
  TickCountParada: Cardinal;
  TickCountParada := GetTickCount;
  while not VerificarTimeOut(TickCountParada, TempoEspera) do

Obs: Do not put a very large sleep because if the thread receives a stop or end signal it will not respond if it is in sleep


Leave a Reply

Your email address will not be published. Required fields are marked *