Insbesondere Thread-Klassen sind ein gutes Beispiel warum Properties benötigt werden.
Soll auf Variablen vom Hauptthreat und vom Thread der Klasse selbst zugegriffen werden,
ist z.B. eine TCriticalSection notwendig, damit es nicht zu Konflikten kommt.
Delphi-Quellcode:
type
TMyThread = class(TThread)
constructor Create;
destructor Destroy; override;
private
FCS: TCriticalSection;
FValue1: Integer;
FValue2: string;
function GetValue1: Integer;
function GetValue2: string;
procedure SetValue1(AValue: Integer);
procedure SetValue2(AValue: string);
public
property CS: TCriticalSection read FCS;
property Value1: Integer read GetValue1 write SetValue1;
property Value2: string read GetValue2 write SetValue2;
procedure ReadFromStream(AStream: TStream);
procedure WriteToStream(AStream: TStream);
end;
constructor TMyThread.Create;
begin
inherited;
FCS := TCriticalSection.Create;
end;
destructor TMyThread.Destroy;
begin
FCS.Free;
inherited;
end;
function TMyThread.GetValue1: Integer;
begin
CS.Enter;
try
Result := FValue1;
finally
CS.Leave;
end;
end;
function TMyThread.GetValue2: string;
begin
CS.Enter;
try
Result := FValue2;
finally
CS.Leave;
end;
end;
procedure TMyThread.SetValue1(AValue: Integer);
begin
CS.Enter;
try
FValue1 := AValue;
finally
CS.Leave;
end;
end;
procedure TMyThread.SetValue2(AValue: string);
begin
CS.Enter;
try
FValue2 := AValue;
finally
CS.Leave;
end;
end;
procedure TMyThread.ReadFromStream(AStream: TStream);
begin
{Zugriffe anderer Threads sperren}
CS.Enter;
try
{Value1 lesen}
{Value2 lesen}
finally
CS.Leave;
end;
{Zugriffe von anderen Threads wieder frei}
end;
procedure TMyThread.WriteToStream(AStream: TStream);
begin
{Zugriffe anderer Threads sperren}
CS.Enter;
try
{Value1 speichern}
{Value2 speichern}
finally
CS.Leave;
end;
{Zugriffe von anderen Threads wieder frei}
end;