-
Notifications
You must be signed in to change notification settings - Fork 62
/
Copy pathOpenAI.Utils.ObjectHolder.pas
112 lines (89 loc) · 2.25 KB
/
OpenAI.Utils.ObjectHolder.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
unit OpenAI.Utils.ObjectHolder;
interface
uses
System.Classes, System.SysUtils, System.Threading;
type
THolder = class(TComponent)
private
FHold: TComponent;
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
procedure HoldComponent(AComponent: TComponent);
function IsLive: Boolean;
end;
IComponentHolder = interface
['{FBCA20CB-E6BB-403B-877C-230F4D343A17}']
procedure HoldComponent(AComponent: TComponent);
function IsLive: Boolean;
end;
TComponentHolder = class(TInterfacedObject, IComponentHolder)
private
FHolder: THolder;
public
procedure HoldComponent(AComponent: TComponent);
function IsLive: Boolean;
constructor Create(AComponent: TComponent = nil);
destructor Destroy; override;
end;
function TaskRun(const Owner: TComponent; Proc: TProc<IComponentHolder>): ITask;
procedure Queue(Proc: TThreadProcedure);
procedure Sync(Proc: TThreadProcedure);
implementation
function TaskRun(const Owner: TComponent; Proc: TProc<IComponentHolder>): ITask;
var
ObjectHold: IComponentHolder;
begin
ObjectHold := TComponentHolder.Create(Owner);
Result := TTask.Run(
procedure
begin
Proc(ObjectHold);
end);
end;
procedure Queue(Proc: TThreadProcedure);
begin
TThread.Queue(nil, Proc);
end;
procedure Sync(Proc: TThreadProcedure);
begin
TThread.Synchronize(nil, Proc);
end;
{ THolder }
procedure THolder.HoldComponent(AComponent: TComponent);
begin
FHold := AComponent;
AComponent.FreeNotification(Self);
end;
function THolder.IsLive: Boolean;
begin
Result := Assigned(FHold);
end;
procedure THolder.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
if Operation = opRemove then
if AComponent = FHold then
FHold := nil;
end;
{ TComponentHolder }
constructor TComponentHolder.Create(AComponent: TComponent);
begin
inherited Create;
FHolder := THolder.Create(nil);
FHolder.HoldComponent(AComponent);
end;
destructor TComponentHolder.Destroy;
begin
FHolder.Free;
inherited;
end;
procedure TComponentHolder.HoldComponent(AComponent: TComponent);
begin
FHolder.HoldComponent(AComponent);
end;
function TComponentHolder.IsLive: Boolean;
begin
Result := FHolder.IsLive;
end;
end.