简体   繁体   中英

High USB-Rate causes error in consuming data

I have an application built with .net core and raspberry pi (compute module 4) with raspberry pi OS. I have two threads, each one responsible for receiving data of (200 bytes) from different USB port every 0.5 millisecond. When only one thread is working, everything is OK, but when two threads are working together this gives me exception while reading from serial buffer, which cause losing in data.

Are there any limits for Linux USB buffers? Or there is another concern should be considered for this practice? Or there is any memory issue?

Code of Receiving:

try
{
int availableBytes = serialPort.BytesToRead;

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

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

return receivedBytes;
}
}
catch (Exception ex)
{

}

Exception:

  • Error Exception Message: The operation has timed out.
  • Exception StackTrace: at System.IO.Ports.SerialStream.Read(Byte[] array, Int32 offset, Int32 count, Int32 timeout) at System.IO.Ports.SerialPort.Read(Byte[] buffer, Int32 offset, Int32 count) at MainBoardSW.HAL.Serial.UsbDriver.ReadAvailableData() in F:\MainBoardSW\HAL\Serial\UsbDriver.cs:line 126

Thank you.

Keep in mind that the SerialPort.Read() method is not guaranteed to read all the bytes reported available by the SerialPort.BytesToRead property . The SerialPort.Read() method returns an integer which indicates the number of bytes that were acctually read. See the "Remarks" section of the SerialPort.Read() reference page for more details. There are many ways to deal with this anomaly one of which is shown below.

    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)
    {
    
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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