111,093
社区成员




BlockingCollection<byte> dataQueue = new BlockingCollection<byte>();
SerialPort port = new SerialPort();
byte[] buffer =new byte[1024];
port.DataReceived += (s, e) =>
{
//assume the bytes to read won't larger than 1024 bytes
if(port.BytesToRead > 0)
{
int readCount = port.Read(buffer, 0, port.BytesToRead);
for(int i=0;i<readCount;i++)
{
//enqueue data
dataQueue.Add(buffer[i]);
}
}
};
//A standalone task to handle the message data
Task.Factory.StartNew(() =>
{
List<byte> msgBuffer = new List<byte>();
const int MSGSIZE = 64;
foreach(var data in dataQueue.GetConsumingEnumerable())
{
msgBuffer.Add(data);
if(msgBuffer.Count == MSGSIZE)
{
//todo
msgBuffer.Clear();
}
}
});