3

i tried one of the solutions in this thread Detecting USB drive insertion and removal using windows service and c#. but i stil get errors, because of the thread-unsafe call to windows forms control.

here is my code

private void initWatchers()
{

    WqlEventQuery insertQuery = new WqlEventQuery("SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_USBHub'");

    ManagementEventWatcher insertWatcher = new ManagementEventWatcher(insertQuery);
    insertWatcher.EventArrived += new EventArrivedEventHandler(DeviceInsertedEvent);
    insertWatcher.Start();

    WqlEventQuery removeQuery = new WqlEventQuery("SELECT * FROM __InstanceDeletionEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_USBHub'");
    ManagementEventWatcher removeWatcher = new ManagementEventWatcher(removeQuery);
    removeWatcher.EventArrived += new EventArrivedEventHandler(DeviceRemovedEvent);
    removeWatcher.Start();

}

and in the event handlers i started the backgroundworker

private void DeviceInsertedEvent(object sender, EventArrivedEventArgs e)
{ 
  this.backgroundWorker1.RunWorkerAsync();
}
void DeviceRemovedEvent(object sender, EventArrivedEventArgs e)
{
 this.backgroundWorker1.RunWorkerAsync();
}

after the backgroundworker is finished, i do access the controls in the windows form

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// access some controls of my windows form
}

so now im still getting errors because of the unsafe calling of the controls. any idea why?

Community
  • 1
  • 1
Orientos
  • 151
  • 3
  • 15

1 Answers1

0

This is because GUI elements are in GUI thread of your app and you are trying to access them from the BackGroundWorker thread. You must use Delegates for working with GUI elements from your BackgroundWorker. For example:

    GUIobject.Dispatcher.BeginInvoke(
        (Action)(() => { string value = myTextBox.Text; }));

On RunWorkerCompleted you are still trying to access GUI elements from the BackGroundWorker.

  • but in the examples of backroundworker here : https://msdn.microsoft.com/de-de/library/system.componentmodel.backgroundworker(v=vs.110).aspx there are no need to use delegates. what is now the right solution? – Orientos Jun 23 '15 at 08:37