Correct thread destroy

Andrew Kalashnikov picture Andrew Kalashnikov · Sep 24, 2010 · Viewed 8k times · Source

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?

Answer

Linas picture Linas · Sep 24, 2010

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);