procedure TfrmMIB.btnSampleClick(Sender: TObject);
var
strBuffer: string;
//strBuffer: PChar;
begin
strBuffer := btnSample.Caption;
//btnSample.GetTextBuf(strBuffer,2);
if AnsiStrComp(PChar(strBuffer),'B') =0 then
begin
btnSample.Caption := 'E';
tDisp.Resume;
//messagebox(0,'b','',MB_OK);
end;
if AnsiStrComp(PChar(strBuffer),'E') =0 then
begin
btnSample.Caption := 'B';
tDisp.Suspend; //出错
//messagebox(0,'E','',MB_OK);
end;
end;
var
strBuffer: string;
//strBuffer: PChar;
begin
strBuffer := btnSample.Caption;
//btnSample.GetTextBuf(strBuffer,2);
if AnsiStrComp(PChar(strBuffer),'B') =0 then
begin
btnSample.Caption := 'E';
tDisp.Resume;
//messagebox(0,'b','',MB_OK);
end;
if AnsiStrComp(PChar(strBuffer),'E') =0 then
begin
btnSample.Caption := 'B';
tDisp.Suspend; //出错
//messagebox(0,'E','',MB_OK);
end;
end;
應該在每個 if 裹面的最後, 加 exit;
unit DISPLAY;interfaceuses
Classes,Windows,SysUtils;type
TDisplay = class(TThread)
private
{ Private declarations }
flgThreadExit : Boolean;
strTemp : string;
procedure Receives;
procedure ExtractString(pHandle: PChar); protected
procedure Execute; override;
procedure DoVisualDisplay;
public
constructor Create(CreateSuspended: Boolean);
end;var
tDisp: TDisplay;implementationuses MIB;{ Important: Methods and properties of objects in visual components can only be
used in a method called using Synchronize, for example, Synchronize(UpdateCaption); and UpdateCaption could look like, procedure TDisplay.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end; }{ TDisplay }constructor TDisplay.Create(CreateSuspended: Boolean);
begin
flgThreadExit := FALSE;
FreeOnTerminate:=True;
inherited Create(CreateSuspended);
end;procedure TDisplay.Execute;
begin
{ Place thread code here }
Receives;
end;procedure TDisplay.Receives;
var
inBuff : array[0..2047] of Char;
BytesRead, dwError : LongWORD;
cs : TCOMSTAT;
i: Integer;
begin
while (flgThreadExit = FALSE) do
begin
ClearCommError(MIB.hSerialPort, dwError, @cs);
if cs.cbInQue>sizeof(inBuff) then
begin
PurgeComm(MIB.hSerialPort, PURGE_RXCLEAR);
exit;
end;
ReadFile(MIB.hSerialPort, inBuff, cs.cbInQue, BytesRead, nil);
strTemp:=Copy(inBuff, 1, cs.cbInQue);
sleep(30);
i:=strlen(PChar(strTemp));
{MessageBox(0,
PChar(inttostr(i)),
'',
MB_OK); }
if strlen(PChar(strTemp))>30 then
ExtractString(PChar(strTemp));
Synchronize(DoVisualDisplay);
end;
end;procedure TDisplay.DoVisualDisplay;
begin
MIB.frmMIB.panDisplay.Caption:= strTemp;
{ if (MIB.hSerialPort = INVALID_HANDLE_VALUE) then
begin
flgThreadExit := TRUE;
CloseHandle(hSerialPort);
exit;
end;
}
end;procedure TDisplay.ExtractString(pHandle: PChar);
var
strExtraTemp: string;
begin
strExtraTemp := pHandle;
{if AnsiStrComp(AnsiStrScan(pHandle,'='),'=') =0 then
begin
MessageBox(0,
AnsiStrScan(pHandle,'='),
'',
MB_OK);
end;}
end;
end.
是不是mid在线程挂起时需要释放啊
ReadFile(MIB.hSerialPort, inBuff, cs.cbInQue, BytesRead, nil);
你用ReadFile, 沒用异步讀取方式, 所以一直阻塞在等待數據!
建議看下Msdn關于 ReadFile使用介紹, 然後, 加入异步處理, 用WaitForSingleObject等來處理!!!