I need a single background thread for my application . If triggered it will simply do some queries against a SQL Database and update another Table . For the sake of simplicity I built myself a Test project to test out my idea . And I came up with the following code :
unit uMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TBackGroundThread = class(TThread)
protected
procedure Execute; override;
end;
type
TMain = class(TForm)
Memo1: TMemo;
btnStartThread: TButton;
Memo2: TMemo;
procedure btnStartThreadClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
var
BackGroundThread : TBackGroundThread;
SafeToStart : boolean;
procedure ShowID;
public
{ Public declarations }
end;
var
Main: TMain;
implementation
{$R *.dfm}
procedure TBackGroundThread.Execute;
begin
Main.SafeToStart:=false;
Main.ShowID;
Main.SafeToStart:=true;
end;
procedure TMain.FormCreate(Sender: TObject);
begin
SafeToStart:=true;
end;
procedure TMain.ShowID;
var i : integer;
begin
for i := 0 to 10 do
begin
sleep(100);
end;
Memo1.Lines.Add(IntToStr(BackGroundThread.ThreadID));
Main.SafeToStart:=true;
end;
procedure TMain.btnStartThreadClick(Sender: TObject);
begin
if SafeToStart = true then
begin
BackGroundThread := TBackGroundThread.Create(false);
BackGroundThread.FreeOnTerminate:=true;
end
else
begin
Memo2.Lines.Add('OOPS' +IntToStr(BackGroundThread.ThreadID));
end;
end;
end.
I am using Private Global Variable to check if it is OK to start or not , I thought this should be safe because I only have one Background task. The Execute will be inside a try except end block.
I tried to check if I have memory leaks , but Delphi did not report any.
My question is :
if I set the FreeOnTerminate property to true, then after the execute the Thread will automatically free itself ?
Thank you.
UPDATE 1
As for the VCL Manipulation from within the thread I will use this :
TThread.Synchronize(TThread.CurrentThread,
procedure
begin
seriesQM.AddXY(qryStat.FieldByName('CurrentPeriod').AsDateTime,qryStat.FieldByName('GesCutQM').AsFloat,
qryStat.FieldByName('Hour').AsString,$00FF9F40);
end);