Multithreading – do I have to signal an anonymous thread if the main thread completes?

Is it necessary to explicitly stop all threads prior to exiting a Win32 Application? 5

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 does not share any resources with the main thread. It just sits there and runs "forever"

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

If you just start a new VCL application, please paste the above code in the formcreate event, which will write my debugging message every half second When the application exits (that is, by closing the form), it appears that the thread also exits, although it does not check for any signals

Never mind, or do I have to use tevent or similar methods to implement some signals to notify the thread?

Or write a custom TThread descendant and leave the thread reference to the thread Will free be better in the future?

Solution

You need to terminate any thread you create, even anonymous threads, for example:

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;
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>