Search code examples
multithreadingdelphidestroy

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?


Solution

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