How to add Sender parameter in thread onterminate?

Asked

Viewed 243 times

0

I have a thread that performs a action and in onterminate performs a secondary process.

It works that way:

procedure qualquer;
var
  Thread: TThread;
begin

  Thread.CreateAnonymousThread(
  procedure()
  begin

    excecuta ação  

  end;

  //como quero que fique - adicionando parametros
  Thread.OnTerminate:= concluiacao(parametro sender, outro parametro);

  //como faço
  Thread.OnTerminate:= concluiacao;

  Thread.Start;

end;  

then I run the second trial

procedure concluiacao(Sender: TObject);
begin

  if TThread(Sender).FatalException <> nil then
  begin
    ShowMessage(TThread(Sender).FatalException.ToString);
    Exit;
  end
  else
    continua os processos normalmente;

end;

I would like to send new parameters in the thread onterminate, but the first parameter is a Sender, and I don’t know how to send it.

  • var Thread: Tthread; --> here must be a descendant of Tthread.

  • Sender is Thread itself. You can declare properties on the descendant and read their values in Onterminate. Just make a Typecast.

  • I even tried some codes as a conclusion(Thread), conclusion(Tthread(Thread)) or conclusion(Tobject(Thread)), but they didn’t work.

  • Check out this link: https://stackoverflow.com/questions/34890222/createanonymousthread-with-parameters

1 answer

1

Using anonymous methods and assigning the Onterminate event, you cannot get any other parameter than Sender, because the method that will be assigned must correspond exactly to the Onterminate function statement expected by Delphi.

Therefore, I would recommend you to declare a class of type Tthread and use the Destroy of the object to get the thread ending so you can control any desired variable.

Behold:

type
  TMinhaThread = class(TThread)
  private
    Parametro1: Integer;
    Parametro2: Boolean;
  protected
    procedure Execute; override;
  public
    destructor Destroy; override;
  end;

procedure TForm1.FormCreate(Sender: TObject);
var Th: TMinhaThread;
begin
    Th := TMinhaThread.Create(True); //criar a thread sem rodá-la
    Th.FreeOnTerminate := True;
    Th.Parametro1 := 100; //atribuir parâmetros internos
    Th.Start; //rodar a thread
end;

{ TMinhaThread }

procedure TMinhaThread.Execute;
begin
  inherited;

  try
    {Fazer procedimentos da thread...}
    Parametro2 := True; //simulando parâmetro
    {...}
  except
    on E: Exception do
      Synchronize(procedure
      begin
        ShowMessage('Erro na thread: '+E.Message);
      end);
  end;
end;

destructor TMinhaThread.Destroy;
begin
  inherited;
  //Aqui é o equivalente ao OnTerminate, porém você tem acesso as propriedades da thread

  if Parametro2 then
    Synchronize(procedure
    begin
      ShowMessage('...');
    end)
  else
    {outro procedimento};
end;

Browser other questions tagged

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