如果你这个线程就起一个定时器的作用,有个轻便的解决方法:
线程定义一个变量
比如ontimer:tnotifyevent;
然后你可以在execute里面写
while not terminated do
begin
sleep(1000);//你需要的interval
if assigned(self.ontimer) then ontimer(self);
end;
这时候,ontimer就在你的新线程里面执行。
当然,最好和服务器通信是"阻塞"的,功能设计得分散些,自定义函数多用些参数,少用共享资源比如全局变量,可以避免很多多线程带来的复杂性。
procedure TTimerThread.Execute;
begin
repeat
if WaitForSingleObject(FStop, FInterval) = WAIT_TIMEOUT then
Synchronize(FOwner.DoTimer);
until Terminated;
end;
{ TThreadedTimer }
constructor TThreadedTimer.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FTimerThread := TTimerThread.Create(True);
with FTimerThread do
begin
FOwner := Self;
FInterval := DEFAULT_INTERVAL;
Priority := tpNormal;
// Event is completely manipulated by TThreadedTimer object
FStop := CreateEvent(nil, False, False, nil);
end;
end;
destructor TThreadedTimer.Destroy;
begin
with FTimerThread do
begin
Terminate;
// When this method is called we must be confident that the event handle was not closed
SetEvent(FStop);
if Suspended then
Resume;
WaitFor;
CloseHandle(FStop); // Close event handle in the primary thread
Free;
end;
inherited Destroy;
end;
procedure TThreadedTimer.DoTimer;
begin
// We have to check FEnabled in the primary thread
// Otherwise we get AV when the program is closed
if FEnabled and Assigned(FOnTimer) then
FOnTimer(Self);
end;
procedure TThreadedTimer.SetEnabled(Value: Boolean);
begin
if Value <> FEnabled then
begin
FEnabled := Value;
if FEnabled then
begin
if FTimerThread.FInterval > 0 then
begin
SetEvent(FTimerThread.FStop);
FTimerThread.Resume;
end;
end
else
FTimerThread.Suspend;
end;
end;
function TThreadedTimer.GetInterval: Cardinal;
begin
Result := FTimerThread.FInterval;
end;
procedure TThreadedTimer.SetInterval(Value: Cardinal);
var
PrevEnabled: Boolean;
begin
if Value <> FTimerThread.FInterval then
begin
// We must restore the previous state of the Enabled property
PrevEnabled := FEnabled;
Enabled := False;
FTimerThread.FInterval := Value;
Enabled := PrevEnabled;
end;
end;
function TThreadedTimer.GetThreadPriority: TThreadPriority;
begin
Result := FTimerThread.Priority;
end;
procedure TThreadedTimer.SetThreadPriority(Value: TThreadPriority);
begin
FTimerThread.Priority := Value;
end;
procedure Register;
begin
RegisterComponents('System', [TThreadedTimer]);
end;