[英]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)
{
}
例外:
谢谢。
请记住,不能保证 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.