Reputation: 851
I'm creating a thread with the basic settings indicated below. Apparently everything is working fine, but when I run MyThread.Terminate
I noticed that Destroy
does not run. Destroy
is only executed when closing the main application.
What is the correct way to end a thread?
BASIC THREAD
// MyThread "TPoolingThread"
constructor TPoolingThread.Create;
begin
inherited Create(True);
// Initializing something
end;
destructor TPoolingThread.Destroy;
begin
inherited Destroy;
end;
procedure TPoolingThread.Execute;
begin
try
while (not Terminated) do begin
sleep(100);
// do something
end;
finally
if not Terminated then
Terminate;
end;
end;
EXECUTING THREAD
// Main Application
//////////////////////////////////////////
// Create and Start
MyThread := TPoolingThread.Create;
if Assigned(MyThread.FatalException) then
raise MyThread.FatalException;
MyThread.Start;
//////////////////////////////////////////
// Stop
MyThread.Terminate;
Upvotes: 1
Views: 1073
Reputation:
I'd like to preface my answer by defining 'ending a thread'. I'm going to assume that by 'ending a thread' you mean to stop your loop in the TPoolingThread.Execute
procedure.
Terminating the thread
The method you use to terminate your thread is perfectly acceptable. Now as to why it is, allow me to show you this snippet:
Version 1
In a Try-Finally construct, the Finally statement is guaranteed to be executed absolutely regardless of what happens in the try clause. However, the Finally clause does not actually handle any exceptions - the program will terminate if no Except clause is found (see notes below).
Therefore if your code within your loop throws an exception, you tell your TPoolingThread
object that it has been terminated.
Why destroy isn't getting called
As Remy Lebeau and Dalija Prasnikar suggest. Terminate is not supposed to call destroy:
System.Classes.TThread.Terminate:
Signals the thread to terminate by setting the Terminated property to true. Terminate sets the thread's Terminated property to true, signaling that the thread should be terminated as soon as possible.
For Terminate to work, the thread's Execute method and any methods that Execute calls should check Terminated periodically and exit when it's true.
I will leave you this link if you want to find out more about ARC in Delphi for Android development.
Upvotes: 1