[英]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.