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

Asked

Viewed 2,247 times

4

Explanation:

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

Problem:

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

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

I thought I’d use one loop simple to run the fade, but how could I measure time without the timer? Does anyone have any idea?

  • 3

    @Pauloroberto why you put the words as code?

  • Because they relate to actions involving code, they are English terms used for a particular achievement, they ask for emphasis. Objective is to facilitate understanding.

  • English terms should be written in italics. Not in code.

  • Why should they? Italics would imply virtually no difference from the rest of the text. - However comments such as these written by me and you are not helping in understanding the question, should be later excluded.

  • 2

    @Pauloroberto in my view, the words fade should be exchanged for the effect of appearing/disappearing/fading. They are not related to the code in any way.

  • What’s the problem with you creating the thread or starting its execution only after the effect is over?

  • I think I explained myself wrong. The effect is called in the middle of the thread.

Show 2 more comments

1 answer

2


You can use the GetTickCount that returns 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 is on for 49.7 days, the cardinal restarts.

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

So you just 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 signal or termination it will not respond if it is in Sleep

Browser other questions tagged

You are not signed in. Login or sign up in order to post.