How to create an Anonymous Thread in Delphi

Asked

Viewed 17,150 times

5

I would like to know how to create an Anonymous Thread in Delphi, if you can show an example I would be grateful.

2 answers

12


Anonymous Thread in Delphi are often used to perform parallel processing.

A good reason to use Thread is when we need to run one or several relatively heavy processes, but we do not want our application to be blocked due to the execution of the same.

To create a Thread we must invoke the method CreateAnonymousThread which creates an instance derived from a Tthread that will simply execute an anonymous tproc method passed as a parameter in the method call.

When we invoke the method CreateAnonymousThread Thread comes with Property FreeOnTerminate default True, which causes the Thread instance to be destroyed after its execution. To keep the Thread created set FreeOnTerminate = False, however you must destroy the Thread instance manually by invoking the Terminate method; It is worth remembering that a Thread is created suspended, to start it you must invoke the method Start().

Another issue we should be careful about is when we need to update the screen, that is, manipulate visual components, so whenever necessary we should use the method synchronize of the Thread where the processes executed within this method are directed to the main thread run, because the objects of the VCL cannot be directly updated in a Thread that is not the main one.

An example:

var 
 myThread : TThread;

begin 

  myThread := TThread.CreateAnonymousThread( procedure begin

     // seu codigo que deseja ser executado dentro da thread


  end);

  myThread.start();

end;

Or else:

begin     
  TThread.CreateAnonymousThread(procedure begin

     // seu codigo que deseja ser executado dentro da thread


  end).start();

end;

5

procedure TForm1.StartThread(const Id, LogId: Integer);
begin
 TThread.CreateAnonymousThread(
    procedure
    var I: Integer;
    begin
      for I := 0 to 100 do
      begin
        Sleep(Random(100));
        LogMsg(Format('Thread: %d; Logitem %d', [Id, I]), LogId);
      end;
    end
    ).Start;
end;

You can use everything in just one set with Start.

Browser other questions tagged

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