2014-11-17 72 views
3

我試過這個線程Detecting USB drive insertion and removal using windows service and c#的解決方案之一。但我仍然得到錯誤,因爲對Windows窗體控件的線程不安全的調用。檢測usb設備插入和刪除在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(); 

} 

,並在事件處理程序,我開始BackgroundWorker的

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 
} 

所以現在我仍然因爲不安全的控件調用而出錯。任何想法爲什麼?

回答

0

這是因爲GUI元素位於您的應用程序的GUI線程中,並且您試圖從BackGroundWorker線程訪問它們。您必須使用委託來處理BackgroundWorker中的GUI元素。例如:

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

在RunWorkerCompleted上,您仍嘗試訪問BackGroundWorker中的GUI元素。

+0

但在這裏的backroundworker的示例中:https://msdn.microsoft.com/de-de/library/system.componentmodel.backgroundworker(v=vs.110).aspx不需要使用委託。現在什麼是正確的解決方案? – Orientos