I have a form Form1 with a button and text box. When I click on the button I should get some data from USB device. For some reason it works correctly only about 2% (I was able to get 2 correct responses out of 100 clicks). Here is the code for the Form1:
namespace Test_onForm1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Lib1.FindHID.TransferInputAndOutputReports(0xC0); //request specific data from USB device
}
}
}
The code handling USB communication is in DLL Lib1 (fragments of the code below):
namespace Lib1
{
public static class FindHID
{
private static void TransferInputAndOutputReports(UInt16 repType)
{
//some code here sending request to USB device... and then read what came from USB
ReadInput();
//some code here
}
// Read an Input report.
private static void ReadInput()
{
Byte[] inputReportBuffer = null;
inputReportBuffer = new Byte[MyHid.Capabilities.InputReportByteLength];
IAsyncResult ar = null;
if (fileStreamDeviceData.CanRead)
{
// RUNS UP TO THIS POINT and then Form1 freezes most of the time
fileStreamDeviceData.BeginRead(inputReportBuffer, 0, inputReportBuffer.Length, new AsyncCallback(GetInputReportData), inputReportBuffer);
}
}
private static void GetInputReportData(IAsyncResult ar)
{
// RARELY GETS HERE
Byte[] inputReportBuffer = null;
inputReportBuffer = (byte[])ar.AsyncState;
fileStremDeviceData.EndRead(ar); //waits for read to complete
// then code to update Form1
}
}
}
}
When it doesn't work it stops around fileStreamDeviceData.BeginRead and then Form1 freezes.
For testing I created a completely new project and instead of using a DLL I copied all DLL code to the Form1. This option works perfectly fine 100% of the time. So my question is why it doesn't work with DLL?
Update: when I get lucky and it start working then it works indefinitely until I close application. Then, I have to keep trying to get it to work again. How to troubleshoot this problem?