C# 关于处理串口数据
这个问题很莫名其妙,我自己也在网上查了些资料,感觉老是没抓住重点,希望懂的人点拨我一下,谢谢。
问题是这样的,点击读取数据按钮,启动两个线程:
...
Thread read = new Thread(new ThreadStart(delegate()
{
ReadPortDataToQueue(串口对象实例ps, 队列ref queue);
}));
Thread write = new Thread (new ThreadStart(delegate()
{
AddDataToDataTable(队列ref queue, 全局临时表ref dt);
}));
read.Start();
write.Start();
...
private void ReadPortDataToQueue(SerialPort sp,Queue<byte[]> queue)
{
sp.ReadToQueue(命令command, ref dt)
}
...
void ReadToQueue(byte[] command,ref Queue<byte[]> queue)
{
for(int i = 0; i < LoopTimes; i++)
{
sp.Write(command,0,4);//给串口发命令;
Thread.Sleep(BUFFER_TIME);//等待数据缓冲好;
byte[] buffer = new byte[sp.BytesToRead];
sp.Read(buffer,0,buffer,Length);
sp.DiscardInBuffer();//情况串口缓冲数据;
queue.Enqueue(buffer);//入队列;
}
sp.Close();
}
...
private void AddDataToDataTable(ref Queue<byte[]> queue, ref DataTable dt)
{
byte[] tempDataStr = null;
while(true)
{
if(queue.Count > 0)
{
tempDataStr = queue.Dequeue();
一个字符串数组 s = TranslateData(tempDataStr);
dr = dt.NewRow();
dr.ItemArray = new Object[] {s[0], ....};
dt.Rows.Add(dr);
}