检测c#中的usb设备插入和删除

时间:2014-11-17 15:23:07

标签: c# usb backgroundworker

我尝试了这个帖子Detecting USB drive insertion and removal using windows service and c#中的一个解决方案。但我仍然得到错误,因为对窗体控件的线程不安全调用。

这是我的代码

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();

}

在事件处理程序中,我启动了后台工作程序

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

在backgroundworker完成后,我会访问windows窗体中的控件

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

因此,由于控件的不安全调用,我现在仍然会收到错误。知道为什么吗?

1 个答案:

答案 0 :(得分:0)

这是因为GUI元素位于应用程序的GUI线程中,并且您正尝试从BackGroundWorker线程访问它们。您必须使用Delegates来处理BackgroundWorker中的GUI元素。例如:

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

在RunWorkerCompleted上,您仍在尝试从BackGroundWorker访问GUI元素。