异步模式下 程序运行一段时间后异常!
我的程序:
unsigned char SendBuffer[4] = {0x02, 0x10, 0x81, 0x6c};
定时器里发送数据:
OVERLAPPED m_ossend;
COMSTAT Cs;
unsigned long nwrite;
memset(&m_ossend,0,sizeof(OVERLAPPED));
m_ossend.hEvent=CreateEvent(NULL,TRUE,FALSE,NULL);
unsigned char number = SendBuffer[0];
DWORD dwErrorFlags;
ClearCommError(HandleCom,&dwErrorFlags,&Cs);
if (WriteFile(HandleCom, SendBuffer, number + 2, &nwrite, &m_ossend) == 0)
{
if(GetLastError()==ERROR_IO_PENDING)
{
WaitForSingleObject(m_ossend.hEvent,1000);
}
}
线程里接受数据:
void __fastcall FR::Execute()
{
while(!Terminated)
{
Synchronize(Receive);
}
}
//---------------------------------------
void __fastcall FR::Receive()//数据接收
{
static double count= 0;
Form1->DisByteMemo->Text = count;
count++;
unsigned char ReceiveBuffer[512] = {0};
unsigned long ReceiveBufferLength = 512;
OVERLAPPED m_osRead;
COMSTAT Cs;
memset(&m_osRead,0,sizeof(OVERLAPPED));
m_osRead.hEvent=CreateEvent(NULL,TRUE,FALSE,NULL);
unsigned long nread;
unsigned long Error;
for (int i = 0;i < ReceiveBufferLength; i++)
{
ReceiveBuffer[i] = 0x00;
}
ClearCommError(HandleCom, &Error, &Cs);
if (Cs.cbInQue > 0 )
{
int temp = min(Cs.cbInQue,ReceiveBufferLength);
if(ReadFile(HandleCom, ReceiveBuffer, temp, &nread, &m_osRead) == false)
{
if(GetLastError()==ERROR_IO_PENDING)
{
WaitForSingleObject(m_osRead.hEvent,2000);
}
}
}
}
我在使用异步模式发送接受数据,开始的20分钟左右,发出数据和接收数据都正常。运行一段时间后,程序抛出异常,然后电脑像司机一样。求大侠给予指点。
[解决办法]
只需定义一个就可以了,然后根据GetLastError函数的返回值进行判断。
像这样的问题最后去VC\MFC版块问,呵呵哪里解答的人会更多些,四处开花嘛