How to check if Anonymous thread is running

4.8k views Asked by At

i want to check if Anonymous thread is running,i have an idea which is to monitor the thread status every 1s, if it Exists, restart the work again..

I've got the thread ID, now how to check the status ?

procedure TForm2.Button5Click(Sender: TObject);
  begin
    TThread.CreateAnonymousThread(procedure   ()
    var i : integer;
    begin
      inc(i);

      label1.caption :=  TThread.Current.ThreadID.ToString;
    end).Start;
  end;
3

There are 3 answers

5
David Heffernan On

Threads do not just stop. If your thread stops functioning it is because your code has a defect. Even the simple code in the question contains two defects. It reads a local variable before it is initialized and it uses a VCL method away from the main thread.

The entire premise of your question is wrong. You don't need to monitor whether or not your thread is still running. You simply need to fix the defects in your code so that it does not fail.

0
Freddie Bell On

A better understanding of what threads are and how to use them, will help you. A thread is usually a way to get something done without holding up the user-interface. If you want the user to wait for something to finish, don't use a thread, just put the work code in the buttonclick event handler without any thread creating.

You said

every 1s, if it Exists, restart the work again

That makes no sense. If the thread exists, it's still busy working so there's no need to restart it. Maybe you should tell us what work you want the thread to do exactly.

In the example below (taken from Background Operations on Delphi Android, with Threads and Timers, you can see that the Synchronize procedure is called when the work is done, so that's how you know that that thread is done with it's work.

procedure TForm2.Button5Click(Sender: TObject);
begin
  TThread.CreateAnonymousThread(procedure ()
  var i : integer;
  begin
    inc(i); // some work here

    TThread.Synchronize (TThread.CurrentThread,
      procedure ()
      begin
        label1.Caption := TThread.Current.ThreadID.ToString;       
      end);

  end).Start;

end;
1
vlad On

TThread.CreateAnonymousThread is a function which returns an instance of new Thread like this:

var ms:TThread;
ms:=TThread.CreateAnonymousThread( .....

You have an instance - ms "aka Thread" and you can work with this object...