[英]filestream c# read data repeatedly
正在使用帶有文件句柄的文件流與USB HID設備通信,設備將在收到報告后重新發送報告(字節[64]的數組)。 接收方法發生在另一個線程中,該線程在讀取報告時觸發事件,
每次嘗試僅發送一次“報告”,第一次嘗試是好的,收到1個報告,但是當我再次發送時,它會讀取兩次! (是否在文件流中兩次可用??)在下一次嘗試時,事件將再次觸發兩次! 之后,將其添加3次,供接下來的3次嘗試
attempt 1 1 report received
attempt 2 2 reports received
attempt 3 2 reports received
attempt 3 3 reports received
attempt 4 3 reports received
attempt 5 3 reports received
attempt 6 4 reports received
attempt 7 4 reports received
發送了更多報告,原因是收到了4個報告,對此有任何邏輯描述嗎?
碼:
private void WriteData(object Data)
{
byte[] data = Data as byte[];
int bytesSent = 0;
while (bytesSent < data.Length)
{
byte [] OutputReportBuffer = new byte[64];
for (int i = 0; i < OutputReportBuffer.Length; i++)
if (bytesSent < data.Length)
{
OutputReportBuffer[i] = data[bytesSent];
bytesSent++;
}
else OutputReportBuffer[i] = 0;
try
{
fileStream.Write(OutputReportBuffer, 0, OutputReportBuffer.Length);
fileStream.Flush();
}
catch///deducted code
}
}
在這里接收到它(讀取數據時觸發事件的單獨線程)
private void ReadData()
{
while (true)
{
try
{
if (fileStream.Read(ReceivedDataBuffer, 0, ReceivedDataBuffer.Length) > 0)
{
_Context.Send(o =>
{
if (DataReceived != null)
DataReceived(this, new DataReceivedEventArgs(ReceivedDataBuffer));
}, null);
}
}
catch //deducted code
}
}
您沒有使用Read
的返回值來查找實際獲得的字節數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.