What is the correct way to interrupt a thread in Delphi

Asked

Viewed 1,737 times

1

I am creating a thread with the basic information and structure as indicated below. Apparently everything is working well, but I noticed that when executing the Terminate, thread does not pass through Destroy. Placing a breakpoint of Destroy I noticed that the thread will only finish effectively when the main application finishes as well. I’m testing on Android and my version of Delphi is 10.2.

BASIC THREAD

// MyThread "TPoolingThread"
constructor TPoolingThread.Create;
begin
   inherited Create(True); // Inicialização suspensa

   // Inicializa algumas coisas
end;

destructor TPoolingThread.Destroy;
begin
   inherited Destroy;
end;

procedure TPoolingThread.Execute;
begin
   try
      while (not Terminated) do begin
         sleep(100);
         // faz algumas coisas
      end;
   finally
      if not Terminated then
         Terminate;
   end;
end;

RUNNING THE THREAD

// Na aplicação principal.... 

   //////////////////////////////////////////
   // Crio e inicializo a thread no BOTÃO 1
   MyThread := TPoolingThread.Create;
   MyThread.Start;

   //////////////////////////////////////////
   // Interrompo a thread no BOTÃO 2
   MyThread.Terminate;
  • 1

    Try setting the property FreeOnTerminate for True. that way when the process she executes ends she’ll destroy herself.

  • 1

    Yeah, I checked that by putting the FreeOnTerminate = True the Destroy is executed, but now the Finally is ignored (occurs only on Android). I found this a strange behavior. Then you get into those questions that we don’t know what decision to make about what the right way to do it is. My concern is that at some point the program starts to have strange behaviors because of a simple incorrect thread release.

  • 1

    If the destroy is executed, is correct finaly be ignored, since the object no longer exists! Most likely the operation will occur correctly.

  • 1

    I’ll watch to see how it behaves. Thank you.

No answers

Browser other questions tagged

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