1、串口接收数据部分

    private void Sp1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {            
            Byte[] receivedData = new Byte[sp1.BytesToRead];
            sp1.Read(receivedData,0, receivedData.Length);

            lock (obj)
            {
                receiveBuf.AddRange(receivedData);
            }
        }

2、线程中处理接收到的数据

    ThreadPool.QueueUserWorkItem(ProData);

全局变量:List<byte> receiveBuf = new List<byte>();
private
void ProData(object state) { List<byte> tmp = new List<byte>(); byte[] _HeaderBuffer = new byte[8]; while (IsOpen) { if (receiveBuf.Count > 8) { receiveBuf.CopyTo(0, _HeaderBuffer, 0, 8);
//根据协议取出总包长
var ilen = RcsMessage.CheckData(_HeaderBuffer);
//如果已经接收到的数据大于一个完整的数据,从ReceiveBuf截取这部分数据工处理,
if (receiveBuf.Count >= ilen&&ilen>10 ) { byte[] receivedata = new byte[ilen]; receiveBuf.CopyTo(0, receivedata, 0, ilen); var str = RcsMessage.ReadData(receivedata); AddContent(str); receiveBuf.RemoveRange(0, ilen); } } Thread.Sleep(100); } }

 

posted on 2022-03-23 19:03  EEEEEEEEEEEEEEEEEEE  阅读(81)  评论(0编辑  收藏  举报