Search code examples
multithreadingdelphisynchronizationdelphi-xe2terminate

Do I have to signal an anonymous thread to exit if the main thread is done?


Suppose I have an anonymous thread that does some background processing:

procedure TForm1.FormCreate(Sender: TObject);
begin
  TThread.CreateAnonymousThread(procedure begin
    while True do begin
      Sleep(500);
      OutputDebugString('I am alive');
    end;
  end).Start;
end;

The thread doesn't share any ressources with the main thread, it just sits there and runs "forever".

Since there is no built-in mechanism like Terminate for anonymous threads, does that mean that I don't have to notify the thread when the main thread of the process exits?

If you just fire up a fresh VCL application an paste the code from above in the FormCreate event it will write I am alive every half second to the debug messages. When the application exits (i. e. by closing the form), it seems that the thread is also exited, despite the fact that it doesn't check for any signal.

Is that ok, or do I have to implement some signal using TEvent or similar to notify the thread?

Or is it better to write a custom TThread descendent and keep a reference to the thread to Thread.Free it later?


Solution

  • You need to terminate any thread you create, even an anonymous thread, eg:

    procedure TForm1.FormCreate(Sender: TObject);
    begin
      TThread.CreateAnonymousThread(procedure begin
        while not Application.Terminated do begin // <--
          Sleep(500);
          OutputDebugString('I am alive');
        end;
      end).Start;
    end;