问题描述
现在在做一个HID的设备通讯项目,读什么的都没问题,一旦写一次,设备就退出了,求解publicboolOpenUSBHid(stringdeviceStr){hidDevice=newFileStream(newSafeFileHandle(device,true),FileAccess.ReadWrite,inputReportLength,true);StateObjectso=newStateObject();so.fs=hidDevice;so.recvData=newbyte[inputReportLength];hidDevice.BeginRead(so.recvData,0,so.recvData.Length,newAsyncCallback(ReadCompleted),so);returntrue;}///<summary>///异步读取结束,发出有数据到达事件///</summary>///<paramname="iResult">这里是输入报告的数组</param>privatevoidReadCompleted(IAsyncResultiResult){StateObjectso=(StateObject)iResult.AsyncState;byte[]readBuff=so.recvData;try{hidDevice.EndRead(iResult);//读取结束,如果读取错误就会产生一个异常byte[]reportData=newbyte[readBuff.Length-1];for(inti=1;i<readBuff.Length;i++)reportData[i-1]=readBuff[i];reporte=newreport(readBuff[0],reportData);OnDataReceived(e);//发出数据到达消息if(!isWrite)//BeginAsyncRead();//启动下一次读操作hidDevice.BeginRead(so.recvData,0,so.recvData.Length,newAsyncCallback(ReadCompleted),so);}catch(ArgumentExceptionex){Console.WriteLine(ex);}catch(IOExceptionex)//读写错误,设备已经被移除{Console.WriteLine(ex);EventArgsea=newEventArgs();OnDeviceRemoved(ea);//发出设备移除消息CloseDevice();}voidEndSendCallback(IAsyncResultar){StateObjectso=(StateObject)ar.AsyncState;FileStreamfs=so.fs;fs.EndWrite(ar);isWrite=false;so.recvData=newbyte[inputReportLength];hidDevice.BeginRead(so.recvData,0,so.recvData.Length,newAsyncCallback(ReadCompleted),so);}voidStartSend(byte[]data){byte[]sendData=newbyte[outputReportLength];hidDevice.BeginWrite(data,0,data.Length,newAsyncCallback(EndSendCallback),newStateObject(){recvData=sendData,fs=hidDevice});}
解决方案
解决方案二:
你的读和写好像都是同一个FileStream,主要是你在读完之后没见你关闭流啊,这样肯定出错。
解决方案三:
异步的过程当中怎么关闭流啊,关闭了以后怎么再打开,而且我设置的流属性是读写双向的