filestream c#重复读取数据

时间:2014-11-19 19:22:37

标签: c# filestream

使用带文件句柄的文件流与USB HID设备进行通信 设备重新发送报告(字节数组[64])收到它。 receive方法发生在另一个线程中,该线程在读取报告时触发事件,

每次尝试只发送一份“报告” 第一次尝试是好的,1收到报告,但是当我再次发送时,它会读取两次! (它在文件流中可用两次吗??) 在下次尝试时,事件再次发射两次! 之后,它会在接下来的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
        }
}

1 个答案:

答案 0 :(得分:0)

您没有使用Read的返回值来查明实际获得的字节数。