Reputation: 41
At the end of a data transfer session with my HID device my software has a ~20% chance to halt on the function WriteFile.
This is written in C#, and I can't figure out why this is happening. A 20% error rate per packet is simply unacceptable and I am having a hard time getting to the bottom of it, I was wondering if it might be something with my declarations or data types?
This is the import
[DllImport("kernel32.dll")]
static public extern int WriteFile(int hFile, ref byte lpBuffer, int nNumberOfBytesToWrite, ref int lpNumberOfBytesWritten, int lpOverlapped);
And this is the call to the function that is halting
Result = USBSharp.WriteFile(hidHandle, ref outputReportBuffer[0], outputReportBuffer.Length, ref NumberOfBytesWritten, 0);
The handle is confirmed to be valid and the rest is fairly self explanatory...
The function simply never returns. I've looked this issue up online a few different locations and mostly nobody's fixes apply to me. I would just thread it and re-call it if it fails but doing that 20% of the time on hundreds of packets is simply... awful.
I am using windows 7, C#, .NET 4.0, and the HID device is not halting it is still active and running - not only that, but the entire data transfer happens properly and this call happens at the very end to complete the transaction and then halts (even though I already have all the data). Unfortunately I can't just ignore this final part of the transaction because this data needs to be 100% maintained or else bad, bad, BAD things will happen to the users.
Upvotes: 4
Views: 2784
Reputation: 1940
If problem persists then you might consider implementing a timeout mechanism:
var stream= new FileStream(hidHandle,FileAccess.Write,false);
var waitEvent= new ManualResetEventSlim();
void Write(byte[] report, int timeout){
waitEvent.Reset();
stream.BeginWrite(report,0,report.Lenght,(ar)=>{stream.EndWrite(ar);waitEvent.Set();},null);
waitEvent.Wait(timeout);
}
Upvotes: 5
Reputation: 35881
Sounds like a problem in the USB driver library. That's the only unique variable in your circumstances. (e.g. lots of people are using WriteFile with USB drives without any problem).
I suggest you contact Florian Leitner for support, or find alternate means of connecting to USB devices. Forian details that it uses the USBSharp class and Scott Hanselman's article so maybe those would be good alternates to start with.
Upvotes: 3
Reputation: 1743
It’s hard to guess what is going wrong here but, here is something important to check/try:
check if you’re calling CreateFile, WriteFile from inside an unsafe context. read more about unsafe code
And to make this unsafe context use unsafe keyword like this:
unsafe static void writeMyFile(...){
...
}
also check the option (Allow unsafe code) in the project properties like this:
i hope this will help.
Upvotes: 2