C# 串行数据丢失?

C# Serial Data Loss?

我学习 C# Serial。 我写这段代码来接收数据。 当我运行这段代码和另一个设备只发送了一次数据,但是程序收到了两次或三次以上的数据。 我该如何解决这个问题?

还有很多我不知道的。请简单地解释一下。 我花了一个星期,因为我无法解决这个问题.... :(

 private void MainForm_Load(object sender, EventArgs e)//main form
        {
            serialPort1.DataReceived += new SerialDataReceivedEventHandler(EventDataReceived);
            CheckForIllegalCrossThreadCalls = false;
                       ........
                       ........
                       ........
        }
                       ........
                       ........
                       ........

void EventDataReceived(object sender, SerialDataReceivedEventArgs e)//this is receiving data method
        {

            int size = serialPort1.BytesToRead;// assign size of receive data to 'int size'

            byte[] buff = new byte[size];// array who assign receiving data(size = int size)
            serialPort1.Read(buff, 0, size);//assign receive data to 'buff'

            string hexData = BitConverter.ToString(buff).Replace("-", " ");//Convert the received data into hexadecimal numbers and store to 'string hexdata'
            for (int i = 0; i < size; i++)
            {
                tb_rx.Text = tb_rx.Text + " \r\n " + hexData;
                Thread.Sleep(1000);//When I first encountered the problem, I added it because I thought the interval was too short. But I don't think this is the solution.
            }
        }

这段代码有问题:

      string hexData = BitConverter.ToString(buff).Replace("-", " ");//Convert the received data into hexadecimal numbers and store to 'string hexdata'
      for (int i = 0; i < size; i++)
      {
           tb_rx.Text = tb_rx.Text + " \r\n " + hexData;
           Thread.Sleep(1000);//When I first encountered the problem, I added it because I thought the interval was too short. But I don't think this is the solution.
       }

BitConverter.ToString(byte[]) 已经将字节数组转换为十六进制字符串序列。在 for 循环中,然后将此 hexData 字符串添加到 tb_rx(可能是文本框) 以接收每个字节 。因此,根据您一次收到的字节数,您会得到重复的输出。只需将其更改为:

string hexData = BitConverter.ToString(buff).Replace("-", " ");//Convert the received data into hexadecimal numbers and store to 'string hexdata'
tb_rx.Text = tb_rx.Text + " \r\n " + hexData;