繁体   English   中英

高 USB 速率导致消费数据错误

[英]High USB-Rate causes error in consuming data

我有一个使用 .net 内核和带有 raspberry pi OS 的 raspberry pi(计算模块 4)构建的应用程序。 我有两个线程,每个线程负责每 0.5 毫秒从不同的 USB 端口接收(200 字节)数据。 当只有一个线程在工作时,一切正常,但是当两个线程一起工作时,这使我在从串行缓冲区读取时出现异常,这会导致数据丢失。

Linux USB 缓冲区是否有任何限制? 还是应该考虑这种做法的另一个问题? 或者有任何 memory 问题?

接收代码:

try
{
int availableBytes = serialPort.BytesToRead;

if (availableBytes > 0)
{
byte[] receivedBytes = new byte[availableBytes];

serialPort.Read(receivedBytes, 0, receivedBytes.Length);

return receivedBytes;
}
}
catch (Exception ex)
{

}

例外:

  • 错误异常消息:操作已超时。
  • 异常 StackTrace:在 System.IO.Ports.SerialStream.Read(Byte[] 数组,Int32 偏移量,Int32 计数,Int32 超时)在 System.IO.Ports.SerialPort.Read(Byte[] 缓冲区,Int32 偏移量,Int32 计数)在 F:\MainBoardSW\HAL\Serial\UsbDriver.cs 中的 MainBoardSW.HAL.Serial.UsbDriver.ReadAvailableData():第 126 行

谢谢。

请记住,不能保证 SerialPort.Read() 方法读取 SerialPort.BytesToRead 属性报告的所有可用字节 SerialPort.Read() 方法返回一个 integer,表示实际读取的字节数。 有关详细信息,请参阅SerialPort.Read() 参考页的“备注”部分。 有很多方法可以处理这种异常,下面显示了其中一种。

    try
    {
        byte[] receivedBytes;
        byte[] tempBuffer;
        int actualBytes = 0;
        int expectedBytes = serialPort.BytesToRead;
        if (expectedBytes > 0)
        {
            tempBuffer = new byte[expectedBytes];
            actualBytes = serialPort.Read(tempBuffer, 0, tempBuffer.Length);
            receivedBytes = new byte[actualBytes];
            System.Array.Copy(tempBuffer, receivedBytes , actualBytes); 
            return receivedBytes;
        }
    }
    catch (Exception ex)
    {
    
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM