使传入数据出队C#

时间:2019-05-13 10:06:15

标签: c# queue backgroundworker

我正在尝试从Com Port获取传感器数据。我使用SerialDataReceivedEventArgs来获取comport数据并将其存储在队列中。数据是连续传输的,所以我使用了backgroundWorker1_DoWork将数据并行出队并存储在文件中。数据格式如下:

  

304,248,16260 \ n 344,124,16252 \ n

我的问题是,当我在此语句string[] str = qdata.Dequeue().Split('\n');后面放置断点以检查str中的数据是否与qdata Queue中接收的数据相同时,我发现它是不同的。附带快照。 enter image description here

str[0]qdata[0]第一个字符没有相同的字母,根据逻辑str[0]应该包含2

为什么会这样或我做错了什么,请帮忙。我的代码如下:

 private void button1_Click(object sender, EventArgs e)
        {
            string abc = comboBox1.SelectedItem.ToString();
            serialPort1.PortName = abc;
            serialPort1.BaudRate = 115200;
            serialPort1.Parity = Parity.None;
            serialPort1.Open();
            backgroundWorker1.RunWorkerAsync();
            serialPort1.DataReceived += new SerialDataReceivedEventHandler(port_receiveddata);


        }
        public void port_receiveddata(object sender, SerialDataReceivedEventArgs e)
        {

            //data = serialPort1.ReadLine().ToString()+'\n';
            data = serialPort1.ReadExisting();
           // data = serialPort1.ReadLine();

            qdata.Enqueue(data);



        }

        private void button2_Click(object sender, EventArgs e)
        {
            serialPort1.Close();            
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            while ((serialPort1.IsOpen)||qdata.Count >0)
            {
                if (qdata.Count > 0)
                {
                    string[] str = qdata.Dequeue().Split('\n');
                    foreach (object item in str)
                    {
                        using (FileStream gf = new FileStream(temp, FileMode.Append, FileAccess.Write))
                        {
                            using (TextWriter pf = new StreamWriter(gf))
                            {
                                pf.Write(item);
                                pf.Write('\n');
                                pf.Close();
                            }
                        }
                    }                  
                }
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (qdata.Count <=0)
            MessageBox.Show("complete");
        }

0 个答案:

没有答案