Tuesday 9 April 2013

How to correctly free a thread

There are 2 ways to free a thread, below are both, but my favourite way is to explicitly free the thread as I may want to reference something after the thread is terminated, but before it is freed.

Explicitly free the thread 
1) Set the 'FreeOnTermiate' property to false, this can be done when your thread class is created. 
2) In the execute procedure check for the terminate property e.g.

while not Terminated do
begin
     // execute code
end;

3) When you want to free the thread do something like:

FThread.Terminate;
FThread.WaitFor;
FreeAndNil(FThread); 

Easier way to free the thread
1) Set the 'FreeOnTermiate' property to true.
2) When you want to free the thread just call:

FThread.Terminate;


No comments:

Post a Comment