3

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?

Community
  • 1
  • 1
Jens Mühlenhoff
  • 14,565
  • 6
  • 56
  • 113

1 Answers1

8

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;
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • This will not necessarily terminate the anonymous thread when the application exits. The odds are higher that the ExitProcess call will terminate the thread in the middle of somewhere in the loop if the loop is doing anything longer than a few ms. – Sertac Akyuz Dec 19 '18 at 19:23
  • True, though there is a small grace period between `Application.Terminated` being set and `ExitProcess()` being called, as the VCL/RTL has to clean itself up first. But you are right. The better solution is to keep track of the thread, and manually terminate it, and wait for it to fully terminate, before then exiting the app. – Remy Lebeau Dec 19 '18 at 19:26