vorgeschlagene Änderungen:
Delphi-Quellcode:
uses Classes, System.SyncObjs;
type
TTestThread =
class(TThread)
private
FTestProperty:
string;
FOnTest: TNotifyEvent;
function GetTestProperty:
string;
procedure SetTestProperty(
const AValue:
string);
protected
FCS: TCriticalSection;
procedure DoTest;
virtual;
procedure Execute;
override;
public
constructor Create(CreateSuspended: Boolean);
destructor Destroy;
override;
{kann aus einem anderen Thread gelesen und verändert werden}
property TestProperty:
string read GetTestProperty
write SetTestProperty;
{wird im Hauptthread aufgerufen (ermöglicht Zugriff auf die VCL)}
property OnTest: TNotifyEvent
read FOnTest
write FOnTest;
end;
implementation
procedure TTestThread.DoTest;
begin
if Assigned(FOnTest)
then // ???: if not Assigned(FOnTest) then
FOnTest(self);
end;
constructor TTestThread.Create(CreateSuspended: Boolean);
begin
inherited Create(CreateSuspended);
FTestProperty := '
default';
FCS := TCriticalSection.Create;
end;
destructor TTestThread.Destroy;
begin
FCS.Free;
inherited;
end;
procedure TTestThread.Execute;
begin
Synchronize(DoTest);
end;
function TTestThread.GetTestProperty:
string;
begin
FCS.Enter;
try
Result := FTestProperty;
finally
FCS.Leave;
end;
end;
procedure TTestThread.SetTestProperty(
const AValue:
string);
begin
FCS.Enter;
try
FTestProperty := AValue;
finally
FCS.Leave;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
FTest := TTestThread.Create(false);
FTest.FreeOnTerminate := false;
FTest.OnTest := MyTest;
FTest.Resume;
repeat
CheckSynchronize(10);
until FTest.Terminated;
Caption := FTest.TestProperty;
FTest.Free;
end;