Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using WriteFile in C# for communication with HID device my program halts

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.

like image 726
B_Moore Avatar asked Dec 26 '22 19:12

B_Moore


1 Answers

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);
}
like image 199
user629926 Avatar answered Feb 26 '23 06:02

user629926