X
ximoyan
Unregistered / Unconfirmed
GUEST, unregistred user!
奇怪的问题:WaitForSingleObject无法响应超时!!!<br>在等待线程里面用WaitForSingleObject判断串口返回信息是否超时,有返回判断会执行,没返回怎么就不会执行呢,应该是在指定时间内无信号量返回就结束等待,继续执行的嘛~!请各位富翁帮看看,弄得我头都大了<br><br>type<br> TTimeOutFun= function(hHandle: THandle; dwOutTime: LONGWORD):integer;<br> <br> //超时等待线程<br> TTimeOutThread=class(TThread)<br> private<br> FProc: pointer;<br> FEvent: THandle;<br> FTimeOut: LongWord;<br> protected<br> procedure Execute; override;<br> procedure SynchProcedcure;<br> public<br> Constructor Create(const AProc: pointer; AEvent: THandle; ATimeOut: LongWord);<br> end;<br><br>{ TTimeOutThread }<br><br>constructor TTimeOutThread.Create(const AProc: pointer; AEvent: THandle; ATimeOut: LongWord);<br>begin<br> FProc:=AProc;<br> FEvent:=AEvent;<br> FTimeOut:=ATimeOut;<br> inherited Create(false);<br>end;<br><br>procedure TTimeOutThread.Execute;<br>begin<br> FreeOnTerminate:=true;<br> Synchronize(SynchProcedcure);<br>end;<br><br>procedure TTimeOutThread.SynchProcedcure;<br>begin<br> if FProc=nil then exit;<br> TTimeOutFun(FProc)(FEvent, FTimeOut);<br>end;<br><br>function JudgeTimeOut(hHandle: THandle; dwOutTime: LONGWORD): integer;<br>begin<br> //if MsgWaitForMultipleObjects(1, hHandle, FALSE, 2000, QS_ALLINPUT)=WAIT_OBJECT_0 then<br> if WaitForSingleObject(hHandle, dwOutTime)=WAIT_OBJECT_0 then //时间参数不为INFINITE <br> begin<br> ShowMessage('返回'); //串口接收到返回还是执行<br> Result:=0;<br> end else<br> begin<br> ShowMessage('超时'); //串口没有接受到根本就不执行,判断好像都没进入啊,如果超过等待时间后是应该执行下面的语句的啊,奇怪!!!<br> Result:=-1;<br> end;<br>end;<br><br>==============================<br>hEvent:THandle;<br>MyThread: TTimeOutThread;<br>创建TComm时同时调用hEvent:=CreateEvent(nil,true,false,nil);<br>发送数据前调用ResetEvent(hEvent)恢复非信号态; <br>同时创建判断超时线程:MyThread := TTimeOutThread.Create(@JudgeTimeOut, hEvent, 1000);<br>接受返回数据后调用SetEvetn(hEvent)设置信号态<br><br>如果把判断超时放在直接放主线程里面每次都是超时,而且主线程处于等待状态,SetEvent(hEvent)无法唤醒调用WaitForSingleObject的主线程