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

4

Explanation:

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 .

Problem:

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?

    
asked by anonymous 19.02.2014 / 17:58

1 answer

2

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
var
  TickCountAtual: Cardinal;
begin
  TickCountAtual := GetTickCount;
  if TickCountInicial <= TickCountAtual then
    Result := (TickCountAtual - TickCountInicial) >= TempoEsperado
  else
    Result := ((MAXCARDINAL - TickCountInicial) + TickCountAtual) >= TempoEsperado;
end;

Then in the thread you do:

procedure EsperaAte(const TempoEspera: Cardinal);
var
  TickCountParada: Cardinal;
begin
  TickCountParada := GetTickCount;
  while not VerificarTimeOut(TickCountParada, TempoEspera) do
    Sleep(10);
end;

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

    
19.02.2014 / 18:04