How to create an Anonymous Thread in Delphi

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

Author: Tmc, 2015-12-23

2 answers

Anonymous threads in Delphi are often used to run parallel processes.

A good reason to use thread is when we need to run one or several relatively heavy processes, but we don't want our application to get stuck due to running them.

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

When we invoke method CreateAnonymousThread The 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, but 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 question we should be careful about is when we need to update the screen, that is, manipulate visual components, so whenever necessary we must 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 VCL can not be directly updated in a Thread other than 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 also:

begin     
  TThread.CreateAnonymousThread(procedure begin

     // seu codigo que deseja ser executado dentro da thread


  end).start();

end;
 12
Author: Eduardo Binotto, 2017-04-11 20:10:27
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.

 5
Author: Wellington Telles Cunha, 2017-04-09 21:24:16