title: HID Device. Best way to do event handling?
body: <p>I'm using an HID device to connect to a CAN bus with several different types of sensors attached. Some of them respond quickly, others have more latency.</p>
  
  <p>I'm using this USB HID Component for C# as a .dll in visual basic, which works great. <a href="http://www.codeproject.com/KB/cs/USB_HID.aspx" rel="nofollow">http://www.codeproject.com/KB/cs/USB_HID.aspx</a></p>
  
  <p>My current code for sending and receiving commands is somewhat troublesome. Sometimes commands and sent but not received fast enough. The problem can be with the sensor, not the actual vb code. We want the program to continue monitoring the other sensors, and not hang for too long.</p>
  
  <p>Currently I'm using event handlers and loops, but I'm wondering if this might be better done by threading? or if my routine is the best for this situation.</p>
  
  <p>Code Snippets:</p>
  
  <p><strong>CANUSB_Class.vb</strong></p>
  
  <pre><code>Public Sub DataReceivedHandler(ByVal sender As Object, ByVal dataReceived As DataRecievedEventArgs)
       For Each byteReceived As Byte In dataReceived.data
           rxDataStruct.dataPacket(rxDataStruct.InPacketLength) = byteReceived
           rxDataStruct.InPacketLength += 1
       Next
       rxDataReady = True
  </code></pre>
  
  <p><strong>MainParsingRoutine.vb</strong></p>
  
  <pre><code>sendCommand = False
  CANPort.rxDataReady = False
       Try
            Do
                Tries += 1
                If Tries &gt; 4 Then
                    Exit Do
                End If
                CANTimer.Start()
                CANPort.transmitPacket(OutCANPacket)
  
                'Wait for Return Packet
                Do Until CANPort.rxDataReady = True Or _ 
                        CANTimer.ElapsedMilliseconds &gt; timeout
                    System.Threading.Thread.Sleep(0)
                Loop
                If CANPORT.rxDataReady = True Then
                    sendCommand = True 
            Loop Until sendCommand = True
  </code></pre>