串列埠通訊,資料會被分多次收到的處理方法
阿新 • • 發佈:2022-03-23
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); } }