Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct thread destroy

Hello At my form I create TFrame at runtime. At this frame I create background thread with executes commands in endless loop. But when I destroy this frame I should destroy this thread. I try

thread.Suspend;
thread.Terminate;
FreeAndNil(thread);

but get AV and ThreadError. How should i destroy thread?

like image 207
Andrew Kalashnikov Avatar asked Sep 24 '10 15:09

Andrew Kalashnikov


3 Answers

You must make sure that the thread exits its Execute method to terminate it properly.

Code could be something like this:

procedure TThread.Execute;
begin
  while not Self.Terminated do
  begin
    //do something
  end;
end;

Call this when You want to destroy thread:

thread.Terminate;
thread.WaitFor;
FreeAndNil(thread);
like image 196
Linas Avatar answered Oct 19 '22 17:10

Linas


It is sufficient to do thread.Terminate. But you will probably want to set thread.FreeOnTerminate := true when it is created.

Of course, in the tight loop of your thread (that is, in Execute), you need to check if the thread has been requested to terminate (check the Terminated property). If you find that the thread has been requested to terminate, simply break from the loop and exit from Execute.

like image 21
Andreas Rejbrand Avatar answered Oct 19 '22 17:10

Andreas Rejbrand


You should never call suspend on a tthread its not safe to do so and resume should only be used to start a thread that was created suspended.

In Delphi 2010 the suspend and resume where depreciated and the method start was introduced to reinforce this.

For a more complete explanation see this thread at Codegears forums.

having said that there are 2 ways I will terminate and free a tthread.

1: I Set FreeOnTerminate when the thread is created so I just call.

Thread.Terminate;

2: Free the thread explicitly, as I need to read a result from a public property before the thread is freed and after it has terminated.

Thread.Terminate;
Thread.WaitFor;
//Do somthing like read a public property from thread object
if Thread <> nil then FreeAndNil(Thread);

In the main execute loop it may be a good idea to put some exception handling in. Or you may be left wondering why the thread appears to terminate its self. This may be causing the AV if the thread is set to FreeOnTerminate and it has already been freed when you try to free it.

procedure TThread.Execute;
begin
  while not Terminated do
  begin
    try
      //do something
    except
      on E:Exception do
       //handle the exception
    end;
  end;
end; 
like image 4
Mike Taylor Avatar answered Oct 19 '22 19:10

Mike Taylor