Author Topic: Calling RegisterForDeviceNotification from background thread?  (Read 14051 times)

bmt22033

  • Member
  • ***
  • Posts: 3
I've got a c# WinForms application built on Jan's generic HID host app (v4.6).  Everything was working as expected until recently when decided to add a background thread (via the BackgroundWorker control) and move parts of the code there to keep my UI responsive.  Now, when my user clicks a button on the form, I start the background thread which, among other things, calls the FindTheHid() method in Jan's original example.  Inside FindTheHid() is this line:

   // MyDeviceManagement.RegisterForDeviceNotifications() will in turn call RegisterForDeviceNotification() and pass in the 2nd, 3rd and 4th args
   success = MyDeviceManagement.RegisterForDeviceNotifications( myDevicePathName, FrmMy.Handle, hidGuid, ref deviceNotificationHandle );

As you can see, the second argument to RegisterForDeviceNotifications() is a handle to the window that will receive events for the device specified in the third argument.  Since this is now being called from a background thread instead of the main UI thread, I'm getting a System.InvalidOperationException ("Cross-thread operation not valid: Control 'FormMain' accessed from a thread other than the thread it was created on.").  Is it possible to execute this from a background thread?

Jan Axelson

  • Administrator
  • Frequent Contributor
  • *****
  • Posts: 3033
    • Lakeview Research
Re: Calling RegisterForDeviceNotification from background thread?
« Reply #1 on: April 10, 2012, 06:52:40 pm »
My first thought would be to move the function back to the form's thread and pass it the needed parameters.

Jan