unit AnonThreadCallback;
interface
uses
System.Classes,
System.SysUtils,
System.SyncObjs;
type
TAnonThreadCallback =
class(TThread)
private
FAction : TProc;
FCallback : TProc;
FSyncedAction : Boolean;
FSyncedCallback : Boolean;
FWorkEvent : TEvent;
protected
procedure Execute;
override;
procedure TerminatedSet;
override;
public
constructor Create(AProc : TProc; Suspended : Boolean = False);
overload;
constructor Create(AProc : TProc; ACallBack : TProc; Suspended : Boolean = False)
overload;
constructor Create(AProc : TProc; ACallBack : TProc; SyncedCallback : Boolean; Suspended : Boolean = False)
overload;
constructor Create(AProc : TProc; SyncedProc : Boolean; Suspended : Boolean = False);
overload;
constructor Create(AProc : TProc; SyncedProc : Boolean; ACallBack : TProc; Suspended : Boolean = False);
overload;
constructor Create(AProc : TProc; SyncedProc : Boolean; ACallBack : TProc; SyncedCallback : Boolean; Suspended : Boolean = False);
overload;
destructor Destroy;
override;
procedure Start();
end;
implementation
{ TAnonThreadCallback }
constructor TAnonThreadCallback.Create(AProc: TProc; SyncedProc: Boolean;
ACallBack: TProc; SyncedCallback : Boolean; Suspended : Boolean);
begin
FWorkEvent := TEvent.Create(
nil, True, False, '
' );
FreeOnTerminate := True;
FAction := AProc;
FSyncedAction := SyncedProc;
FCallback := ACallBack;
FSyncedCallback := SyncedCallback;
inherited Create();
if not Suspended
then Start();
end;
destructor TAnonThreadCallback.Destroy;
begin
FreeAndNil(FWorkEvent);
inherited;
end;
constructor TAnonThreadCallback.Create(AProc, ACallBack: TProc; SyncedCallback,
Suspended: Boolean);
begin
Create(AProc,False,ACallBack,SyncedCallback,Suspended);
end;
constructor TAnonThreadCallback.Create(AProc, ACallBack: TProc;
Suspended: Boolean);
begin
Create(AProc,False,ACallBack,False,Suspended);
end;
constructor TAnonThreadCallback.Create(AProc: TProc; Suspended: Boolean);
begin
Create(AProc,False,
nil,False,Suspended);
end;
constructor TAnonThreadCallback.Create(AProc: TProc; SyncedProc,
Suspended: Boolean);
begin
Create(AProc,SyncedProc,
nil,False,Suspended);
end;
constructor TAnonThreadCallback.Create(AProc: TProc; SyncedProc: Boolean;
ACallBack: TProc; Suspended: Boolean);
begin
Create(AProc,SyncedProc,ACallBack,False,Suspended);
end;
procedure TAnonThreadCallback.Execute;
begin
inherited;
if FWorkEvent.WaitFor()=wrSignaled
then
if not Terminated
then begin
if FSyncedAction
then TThread.Synchronize(
nil,
procedure begin FAction()
end)
else FAction();
if Assigned(FCallback)
then
if FSyncedCallback
then TThread.Synchronize(
nil,
procedure begin FCallback()
end)
else FCallback();
end;
end;
procedure TAnonThreadCallback.Start;
begin
FWorkEvent.SetEvent;
end;
procedure TAnonThreadCallback.TerminatedSet;
begin
inherited;
Start();
end;
end.