Hi again; I have some questions about Threads; my case is: I have a single application, The MainThread and a secondary Thread; The second thread calculate the time each second is like a clock; this have the Synchronize method to help me display the time into my MainForm(MainThread), No problem here, the time is displayed correctly; But sometimes the mainThread try to connect with a db server, sometimes this take 5 seconds; in that time the second thread appear is paused; and start calculated again after connect to database.
I discover that if you don't assign the event that show the time calculated for the second thread; the second thread never paused, and still calculated in that 5 seconds; Thanks
The
Second Thread that calculate the time:
type
{ TMyThread }
TShowStatusEvent = procedure(textTime: TTime; objStatus: boolean) of Object;
TMyThread = class(TThread)
private
vstsObj: boolean;
FOnShowStatus: TShowStatusEvent;
procedure ShowStatus;
protected
procedure Execute; override;
public
constructor Create(CreateSuspended: boolean);
property OnShowStatus: TShowStatusEvent read FOnShowStatus write FOnShowStatus;
Time : TTime;
end;
implementation
constructor TMyThread.Create(CreateSuspended : boolean);
begin
FreeOnTerminate := True;
inherited Create(CreateSuspended);
end;
procedure TMyThread.Execute;
begin
While (not Terminated) do begin
Time := Time + 1/86400; //(24 * 60 * 60);
Synchronize(@Showstatus);
Sleep(1000)
end;
end;
procedure TMyThread.ShowStatus;
begin
if Assigned(FOnShowStatus) then begin
FOnShowStatus(Time, vstsObj);
end;
end;
MainThread:procedure TfrmMainDesk.FormShow(Sender: TObject);
begin
if MyTime = nil then begin
MyTime := TMyThread.Create(True);
MyTime.Time := Now - 30/1440;
MyTime.OnShowStatus := @ShowTime;
MyTime.Resume;
end;
end;
procedure TfrmMainDesk.ShowTime(textTime: TTime; objStatus: boolean);
begin
Label1.Caption := '[ '+ FormatDateTime('hh:mm:ssampm', textTime) + ' ]';
end;