Dann nimm für die Zeitanzeige einen Timer.
Und es geht natürlich auch ohne Synchronize.
Delphi-Quellcode:
interface
uses
Classes, SyncObjs,
Forms, WinXCtrls, StdCtrls, ExtCtrls;
type
TheThread = class(TThread)
constructor Create(CreateSuspendet: Boolean);
destructor Destroy; override;
private
FValue: Integer;
protected
FCS: TCriticalSection;
procedure Execute; override;
function GetValue: Integer;
procedure SetValue(AValue: Integer);
public
property Value: Integer read GetValue write SetValue;
end;
type
TMainForm = class(TForm)
Indicator: TActivityIndicator;
CounterLabel: TLabel;
StartThreadBtn: TButton;
Timer: TTimer;
procedure StartBtnClick(Sender: TObject);
procedure DoOnTimer(Sender: TObject);
procedure DoOnTerminate(Sender: TObject);
private
{ Private-Deklarationen }
FThread: TheThread;
public
{ Public-Deklarationen }
end;
var
MainForm: TMainForm;
implementation
{$R *.dfm}
uses
SysUtils;
// *************************************************
constructor TheThread.Create(CreateSuspendet: Boolean);
begin
FCS := TCriticalSection.Create;
inherited;
end;
destructor TheThread.Destroy;
begin
inherited;
FCS.Free;
end;
procedure TheThread.Execute;
var
I: Integer;
begin
try
for I := 0 to 100 do
begin
Value := I; // MainForm.CounterLabel.Caption
Sleep(500);
end;
except
// hier Fehlerbehandlung aller Fehler im Thread
end;
end;
function TheThread.GetValue: Integer;
begin
FCS.Enter;
try
Result := FValue;
finally
FCS.Release;
end;
end;
procedure TheThread.SetValue(AValue: Integer);
begin
FCS.Enter;
try
FValue := AValue;
finally
FCS.Release;
end;
end;
// *************************************************
procedure TMainForm.StartBtnClick(Sender: TObject);
begin
MainForm.Indicator.Animate := True;
Timer.Enabled := True;
// Thread starten
FThread := TheThread.Create(True);
FThread.FreeOnTerminate := True;
FThread.OnTerminate := DoOnTerminate;
FThread.Resume;
end;
procedure TMainForm.DoOnTimer(Sender: TObject);
begin
if Assigned(FThread) then
begin
MainForm.CounterLabel.Caption := IntToStr(FThread.Value);
end;
end;
procedure TMainForm.DoOnTerminate(Sender: TObject);
begin
MainForm.Indicator.Animate := False;
Timer.Enabled := False;
FThread := nil;
end;
end.