Note: need to read more about using TThread.Synchronize or TThread.Queue
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, AsyncCalls, StdCtrls, ExtCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
mmo1: TMemo;
tmr1: TTimer;
procedure Button1Click(Sender: TObject);
procedure tmr1Timer(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
TMyThread = class(TThread)
protected
procedure Execute; override;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TMyThread.Execute;
begin
form1.mmo1.Lines.add('start threaded timer after wake: '+formatdatetime('hh:mm:ss',now()));
sleep(5000);
form1.mmo1.Lines.add('end threaded timer after wake: '+formatdatetime('hh:mm:ss',now()));
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
TMyThread.Create(False);
end;
procedure TForm1.tmr1Timer(Sender: TObject);
begin
mmo1.Lines.add('regular timer: '+formatdatetime('hh:mm:ss',now()));
end;
end.
To stop a thread that is processing a never-ending loop, you can use a flag to signal the thread to exit. Here’s how you can modify the example to include a mechanism for stopping the thread:
Define a flag in the thread class:
type TMyThread = class(TThread)
private
FStop: Boolean;
protected
procedure Execute; override;
public
procedure Stop;
end;
Implement the Execute method to check the flag:
procedure TMyThread.Execute;
begin
while not Terminated and not FStop do begin
// codes here //
end;
end;
Implement the Stop method to set the flag:
procedure TMyThread.Stop; begin FStop := True; end;
Create and stop the thread from the main form:
var
MyThread: TMyThread;
procedure TForm1.Button1Click(Sender: TObject);
begin
MyThread := TMyThread.Create(False);
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
if Assigned(MyThread) then
begin
MyThread.Stop;
MyThread.WaitFor;
FreeAndNil(MyThread);
end;
end;
In this example:
The FStop flag is used to signal the thread to stop. The Execute method checks the FStop flag in each iteration of the loop. The Stop method sets the FStop flag to True. The main form creates the thread with Button1Click and stops it with Button2Click. This approach ensures that the thread can exit gracefully when the Stop method is called.
Another Solution using Timer Event to do some background task:
unit BackgroundThread;
interface
uses Classes, SysUtils;
type
TBackgroundProcessThread = class(TThread)
protected
procedure Execute; override;
end;
implementation
procedure TBackgroundProcessThread.Execute;
begin
while not Terminated do begin
// Place your CPU-intensive process here
Sleep(10000); // Simulate a 10-second interval
end;
end;
end.
uses BackgroundThread; procedure TForm1.Timer1Timer(Sender: TObject); var BackgroundThread: TBackgroundProcessThread; begin BackgroundThread := TBackgroundProcessThread.Create(True); BackgroundThread.FreeOnTerminate := True; BackgroundThread.Start; end;
