// Delphipraxis.net: https://www.delphipraxis.net/181814-thread-timer-einbinden-von-timerthread-pas.html
unit Shared.Thread.CustomThread;
interface
uses
System.Classes, System.SyncObjs;
const
TIMERTHREAD_INTERVAL_DEFAULT = 1000;
TIMERTHREAD_ENABLED_DEFAULT = True;
type
TCustomThread =
class(TThread)
private
FCS: TCriticalSection;
FEvent: TEvent;
FInterval: Cardinal;
FEnabled: Boolean;
procedure SetInterval(
const Value: Cardinal);
function GetInterval: Cardinal;
procedure SetEnabled(
const Value: Boolean);
function GetEnabled: Boolean;
protected
procedure Execute;
override;
final;
procedure ExecuteTimed;
virtual;
procedure TerminatedSet;
override;
// ACHTUNG! Das gibt es erst ab Delphi XE2
public
constructor Create;
destructor Destroy;
override;
property Interval: Cardinal
read GetInterval
write SetInterval
default TIMERTHREAD_INTERVAL_DEFAULT;
property Enabled: Boolean
read GetEnabled
write SetEnabled
default TIMERTHREAD_ENABLED_DEFAULT;
end;
implementation
{TCustomThread}
constructor TCustomThread.Create;
begin
FCS := TCriticalSection.Create;
FEvent := TEvent.Create(
nil, False, False, '
');
inherited Create(False);
FInterval := TIMERTHREAD_INTERVAL_DEFAULT;
FEnabled := TIMERTHREAD_ENABLED_DEFAULT;
end;
destructor TCustomThread.Destroy;
begin
inherited;
FEvent.Free;
FCS.Free;
end;
procedure TCustomThread.Execute;
var
LInterval: Cardinal;
begin
inherited;
while not Terminated
do
begin
if Enabled
then
LInterval := Interval
else
LInterval := INFINITE;
if FEvent.WaitFor(LInterval) = TWaitResult.wrTimeout
then
ExecuteTimed;
end;
end;
procedure TCustomThread.ExecuteTimed;
begin
end;
function TCustomThread.GetEnabled: Boolean;
begin
FCS.Enter;
try
Result := FEnabled;
finally
FCS.Leave;
end;
end;
function TCustomThread.GetInterval: Cardinal;
begin
FCS.Enter;
try
Result := FInterval;
finally
FCS.Leave;
end;
end;
procedure TCustomThread.SetEnabled(
const Value: Boolean);
begin
FCS.Enter;
try
if Value <> FEnabled
then
begin
FEnabled := Value;
FEvent.SetEvent;
end;
finally
FCS.Leave;
end;
end;
procedure TCustomThread.SetInterval(
const Value: Cardinal);
begin
FCS.Enter;
try
if Value <> FInterval
then
begin
FInterval := Value;
FEvent.SetEvent;
end;
finally
FCS.Leave;
end;
end;
procedure TCustomThread.TerminatedSet;
begin
inherited;
FEvent.SetEvent;
end;
end.