c#有时两次处理相同的串行接收字节

时间:2017-09-11 12:10:33

标签: c# debugging serial-port backgroundworker

我的应用程序正在处理连续接收的字节,我注意到一个奇怪的错误。有时一个字节(总是碰巧是0x03)被处理2次,我不知道为什么。

当我收到一个字节(或几个)时,我使用+= ReadExisting()将它们添加到字符串中。这个字符串形成我的缓冲区后台工作程序处理字符串的所有字节,直到字符串为空。读入后,字符串的第一个元素会被删除,这会使string.Length()在每个循环周期中返回一个较小的数字。

private void serial_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            rxBuffer += serial.ReadExisting(); // adds new bytes to buffer

            try { backgroundWorker1.RunWorkerAsync(); } catch { } // starts background worker if it is not working already.
        }


        private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            while (rxBuffer.Length > 0) 
            {
                byte b = Convert.ToByte(rxBuffer[0]); // reads in the next byte    
                rxBuffer = rxBuffer.Remove(0, 1); // deletes this byte from the string

           // ... code ... does things do the UI and stuff

我确信有些串行字节在while循环2x中运行。我在输出中看到过它。由于某些原因,双字节始终为0x03。请注意,程序中的任何其他位置都不会触及rxBuffer

Bullseye set at (0,2)
2:05:10  << 0x80
2:05:10  << 0x3
2:05:10  << 0x13
Bullseye set at (1,2)
2:05:10  << 0x80
2:05:10  << 0x3
2:05:10  << 0x3 <--- this one should not be there.
Bullseye set at (3,0)
2:05:10  << 0x14
2:05:10  << 0x80
2:05:10  << 0x3
2:05:10  << 0x15
Bullseye set at (3,2)
2:05:10  << 0x80
2:05:10  << 0x3
2:05:10  << 0x16
Bullseye set at (4,2)

为什么会发生这种情况?我该如何解决这个问题?它与异步字节读取和后台工作者???

有关

1 个答案:

答案 0 :(得分:1)

快速&amp; 修复:

private readonly object _lock = new object();
private void serial_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        lock( _lock )
        {
        rxBuffer += serial.ReadExisting(); // adds new bytes to buffer
        }
        try { backgroundWorker1.RunWorkerAsync(); } catch { } // starts background worker if it is not working already.
    }


    private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
    {
        lock( _lock)
        {
        while (rxBuffer.Length > 0) 
        {
            byte b = Convert.ToByte(rxBuffer[0]); // reads in the next byte    
            rxBuffer = rxBuffer.Remove(0, 1); // deletes this byte from the string

       // ... code ... does things do the UI and stuff
       } // end while
       } // end lock

更复杂的解决方案需要有关您的课程的更多信息以及对您的代码进行的更多更改。