How to create an Anonymous Thread in Delphi

3

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

    
asked by anonymous 23.12.2015 / 21:14

2 answers

6

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 more relatively heavy processes, but we do not want our application to be blocked due to its execution.

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

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

Another issue we should be careful of is when we need to refresh the screen, that is, manipulate visual components, so whenever necessary we must use the synchronize method of the Thread where the processes executed within this method are directed to the main Thread run , since VCL objects can not be directly updated on a Thread other than the main Thread.

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;
    
23.12.2015 / 21:14
2
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.

    
09.04.2017 / 23:24