楼上,注意在线程中使用事件,否则你将看到CPU占有率=100%,以下是我的做法,供大家参考,另外,还要适时使用Sleep(dems),dwms可为若干ms,这样可使OS中的其他线程得到响应:
type
TPackComm = class(TThread)
private
FCommNO: Byte;
FSPComm: TSimpleComm;//TSimpleComm is Comm component of myself,in overlapped,but not in multi-threads mode
FCloseEvent: THandle;
....
function WantToTerminate:Boolean;
protected
procedure Execute; override;
procedure ExecCommTask;
public
constructor Create( AOwner: TComponent );
procedure Stop;
procedure AttachComm(SpComm: TSimpleComm);
procedure DeattachComm;
end;
function TPackComm.WantToTerminate:Boolean;//when the event is signaled,the comm thread is asked to terminate.
begin
Result:=WaitForSingleObject( FCloseEvent, 0 ) = WAIT_OBJECT_0;
end;
procedure TPackComm.Stop;
begin
SetEvent(FCloseEvent);
end;
procedure TPackComm.AttachComm(SpComm: TSimpleComm);
begin
FSpComm := SpComm;
FCommNO := SpComm.CommNO;
FSPComm.StopWaitEvent := FCloseEvent;
Resume;
end;
procedure TPackComm.DeattachComm;
begin
Suspend;
FSpComm := nil;
end;
constructor TPackComm.Create( AOwner: TComponent );
begin
FCloseEvent := CreateEvent( nil, True, False, nil );//signal to terminate the thread
inherited Create(True);
end;
procedure TPackComm.Execute;
begin
try
while {True}not Terminated do
begin
if WantToTerminate then break;//the thread close event was signaled?
try
ExecCommTask;
except
on E: Exception do HandleException(E.Message, E.HelpContext);//HandleException of yourself
end;
end;
finally
CloseHandle(FCloseEvent);
end;
end;