问题描述
下面是我写的多线程串口收发的程序但是现在用在客户现场经常抱“非窗体线程错误:listByteReceivedlengthisnotenough”帮帮忙,我试了好几种方法都没用publicvoidOpen(intbaudRate,intdataBits,Parityparity,StopBitsstopBits){if(threadRead!=null){threadRead.Abort();}if(systemTimer!=null){systemTimer.Dispose();}if(serialPort!=null){serialPort.Close();serialPort.Dispose();}this.IsOpen=false;this.serialPort=newSerialPort(this.PortName);this.BaudRate=baudRate;this.DataBits=dataBits;this.Parity=parity;this.StopBits=stopBits;try{threadRead=newThread(Read);threadRead.IsBackground=true;threadRead.Start();if(!serialPort.IsOpen){serialPort.Open();}serialPort.DiscardInBuffer();serialPort.DataReceived+=newSerialDataReceivedEventHandler(serialPort_DataReceived);this.IsOpen=true;systemTimer=newSystem.Timers.Timer(500);systemTimer.Elapsed+=newSystem.Timers.ElapsedEventHandler(systemTimer_Elapsed);systemTimer.Start();}catch(Exceptionex){throwex;}}voidserialPort_DataReceived(objectsender,SerialDataReceivedEventArgse){intn=serialPort.BytesToRead;byte[]buffer=newbyte[n];serialPort.Read(buffer,0,n);listByteReceived.AddRange(buffer);serialPort.DiscardInBuffer();}publicvoidWrite(byte[]bytesData){if(IsOpen){try{serialPort.Write(bytesData,0,bytesData.Length);}catch(Exceptionex){throwex;}}else{thrownewApplicationException("SerialPortisClosing!");}}privatevoidRead(){try{while(true){Thread.Sleep(1);lock(locker){if(listByteReceived.Count>0){MissingCount=0;if(!HasConnected){HasConnected=true;}if(listByteReceived[0]==MessageHelper.StringToByte("$")[0]){if(listByteReceived.Count<=4){continue;}Thread.Sleep(5);lock(locker){//报文字节数1字节intdatagramLength=listByteReceived.Skip(3).Take(1).ToArray()[0];//加上两位CRC校验的长度datagramLength+=2;if(listByteReceived.Count>=datagramLength){byte[]bytesDatagram=newbyte[datagramLength];listByteReceived.CopyTo(0,bytesDatagram,0,datagramLength);listByteReceived.RemoveRange(0,datagramLength);Model.IResponseDatagramresp=DatagramFactory.Create(bytesDatagram,this):}else{UserHelper.goyes=0;}}}else{listByteReceived.RemoveAt(0);UserHelper.goyes=0;}}}}}catch(Exceptionex){throwex;}}
解决方案
解决方案二:
通讯程序调试,最直接有效的方式就是逐条打出接收、发送数据,同时输出到文本中靠猜是猜不出来的
解决方案三:
listByteReceivedlengthisnotenough很明显你队列长度不够