detecting usb-device insertion and removal in c#

陌路散爱 提交于 2019-12-06 08:13:19

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/26975946/detecting-usb-device-insertion-and-removal-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!