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

c#有时会两次处理相同的串行接收字节,c#,debugging,serial-port,backgroundworker,C#,Debugging,Serial Port,Backgroundworker,我的应用程序正在处理串行接收的字节,我注意到一个奇怪的错误。有时一个字节(总是0x03)会被处理2x,我不知道为什么 当我收到一个字节(或几个字节)时,我使用+=ReadExisting()将它们添加到字符串中。这个字符串构成了我的缓冲区。后台工作进程处理字符串的所有字节,直到字符串为空。字符串的第一个元素在读入后被删除,这使得string.Length()每隔一个while循环周期返回一个较小的数字 private void serial_DataReceived(object sender,

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

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

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)
Bullseye设置为(0,2)

2:05:10要快速修复&脏的问题:

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

更复杂的解决方案需要更多关于类的信息和对代码所做的更改。

您在两个线程上共享一个资源。你需要同步。或者更好:使用线程安全缓冲区。可能是在执行删除操作时发生了读取事件。当事件发生时,您必须确保它不会干扰内嵌代码。如果您想知道这是否确实是线程问题,请同时输出当前线程id和缓冲区长度…Tnx它似乎可以工作。我的解决方案是调用while循环函数并放弃后台工作程序。我不知道什么会“不那么糟糕”