求助:串口编程用到线程时,CPU使用率达到100%,怎么解决?(在线等待)
源代码如下:
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "Unit2.h"
#include "Unit1.h"
#pragma package(smart_init)
extern HANDLE hComm;
//---------------------------------------------------------------------------
// Important: Methods and properties of objects in VCL can only be
// used in a method called using Synchronize, for example:
//
// Synchronize(UpdateCaption);
//
// where UpdateCaption could look like:
//
// void __fastcall Unit2::UpdateCaption()
// {
// Form1->Caption = "Updated in a thread";
// }
//---------------------------------------------------------------------------
__fastcall TReadThread::TReadThread(bool CreateSuspended)
: TThread(CreateSuspended)
{
}
//---------------------------------------------------------------------------
void __fastcall TReadThread::Execute()
{ //---- Place thread code here ----
while (! Terminated)
Synchronize(ReadData);
}
//---------------------------------------------------------------------------
void __fastcall TReadThread::ReadData()
{
String Temp;
char inbuff[1024];
DWORD nBytesRead, dwEvent,dwTrans,dwError;
COMSTAT cs;
if (hComm == INVALID_HANDLE_VALUE)
return;
ClearCommError(hComm,&dwError,&cs); //取得状态
if (cs.cbInQue > sizeof(inbuff)) // 数据是否大于我们所准备的Buffer
{ PurgeComm(hComm, PURGE_RXCLEAR); // 清除COM 数据
return;
}
ReadFile(hComm,inbuff,cs.cbInQue,&nBytesRead,NULL); // 接收COM 的数据
inbuff[cs.cbInQue]= '\0'; // 转移数据到变量中
if (strlen(inbuff)>0) // 将数据显示在Memo1上
Form1->mReceive->Text = Form1->mReceive->Text + inbuff;
}
//--------------------------------------------------------------------------