HidLibrary
HidLibrary copied to clipboard
Multithreading
There seems to be an issue with using this library in a multithread application. In my example, I find the device in one thread and spawn a new thread for opening, reading, and writing to the USB device. No other thread will access the device. The WriteReport method works fine, but the ReadReport method always times out or sends back no data in the report. I am using a USB analyzer to verify the reports are being sent and reports are coming in.
I have the same issu...
There is a easy workaround: use two different handles (open the interface two times) for sending and receiving data. Also a blocking read reader thread aligns the received HID data on fast device correctly. The async callback option is a bit to slow with HID msg each millisecond.
private void openDevice()
{
if(myRecvThread != null && myRecvThread.IsAlive)
{
myRecvThread.Abort();
}
HidFastReadEnumerator enumerator = new HidFastReadEnumerator();
readDevice = (HidFastReadDevice) enumerator.Enumerate(VendorId, ProductId).FirstOrDefault();
if (readDevice != null)
{
//make a copy of the device for different write actions
writeDevice = (HidFastReadDevice)enumerator.GetDevice(readDevice.DevicePath);
writeDevice.OpenDevice(DeviceMode.Overlapped, DeviceMode.Overlapped, ShareMode.ShareRead | ShareMode.ShareWrite);
readDevice.OpenDevice();
readDevice.MonitorDeviceEvents = true;
readDevice.Inserted += DeviceAttachedHandler;
readDevice.Removed += DeviceRemovedHandler;
myRecvThread = new Thread(() => RealStart(readDevice));
myRecvThread.Start();
}
}
private static void RealStart(HidFastReadDevice threadDevice)
{
while (true)
{
HidDeviceData data;
data = threadDevice.Read(100);
if (data.Status == HidDeviceData.ReadStatus.Success)
Console.WriteLine(ByteArrayToString(data.Data));
}
}
Best regards
Sebastian