I've been trying to to set the FreeOnTerminate
property in the OnTerminate
procedure but it seems like it's either too late to set it or it's completely ignoring the write
procedure.
How can I set/change the FreeOnTerminate
property in the OnTerminate
procedure?
Are there any workarounds for that?
A little code:
unit Unit2;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TForm2 = class(TForm)
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
procedure OnTestThreadTerminate (Sender : TObject);
public
{ Public declarations }
end;
type
TTestThread = class (TThread)
public
procedure Execute; override;
end;
var
Form2: TForm2;
GlobalThreadTest : TTestThread;
implementation
{$R *.dfm}
procedure TForm2.Button1Click(Sender: TObject);
begin
GlobalThreadTest := TTestThread.Create (True);
GlobalThreadTest.OnTerminate := Self.OnTestThreadTerminate;
GlobalThreadTest.FreeOnTerminate := True;
GlobalThreadTest.Resume;
end;
procedure TForm2.Button2Click(Sender: TObject);
begin
// 2nd Button to try to free the thread...
// AFTER BUTTON1 has been clicked!
try
GlobalThreadTest.Free;
except
on e : exception do begin
MessageBox(Self.Handle, pchar(e.Message), pchar(e.ClassName), 64);
end;
end;
end;
procedure TForm2.OnTestThreadTerminate(Sender: TObject);
begin
TTestThread(Sender).FreeOnTerminate := False; // Avoid freeing...
ShowMessage (BoolToStr (TTestThread(Sender).FreeOnTerminate, True)); // FreeOnTerminate Value has been changed successfully!
end;
procedure TTestThread.Execute;
begin
// No code needed for test purposes.
end;
end.