2014-05-04 47 views
0

我有這段代碼時:RPC_E_CANTCALLOUT_ININPUTSYNCCALL試圖訪問USB設備

var searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_DiskDrive");    
foreach (var queryObj in searcher.Get().Cast<ManagementObject>()) //Error points to this line 

基本上這個代碼是什麼,它貫穿連接的設備的列表,如果一個我想連接樣子。 如果我在代碼運行時已連接設備的情況下運行此代碼,那麼它完美地工作。 但是,如果我觸發與DBT_DEVICEARRIVAL這個代碼(其是事件時一些裝置連接在系統發送和我抓住它與

private static IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled){if(..DBT_DEVICEARRIVAL..) new ScanDevices(); /*Here lies the code from above (in the class)*/} 

)我得到這個錯誤:

的呼出呼叫不能因爲進行應用程序正在調度輸入同步調用。 (來自HRESULT的異常:0x8001010D(RPC_E_CANTCALLOUT_ININPUTSYNCCALL))。

如果我把thread.sleep(5000)放在上面的代碼的頂部,所以它在執行前等待5秒鐘,然後代碼工作。因此,衝突必須在某個地方,其他事情先嚐試訪問該設備,然後爲其自己。

我搜索了互聯網,發現了一些建議,比如向自己發送自定義postmessage來觸發代碼,但是我對如何實現這一點甚至是如何解決問題一無所知。

這裏最好的解決方案是什麼?

+0

這是可以被誘導線程的一個問題。你的問題沒有提及任何有關你創建什麼樣的線程或什麼類型的應用程序(控制檯與GUI)的細節。細節很重要。 –

+0

我沒有在該應用程序中使用線程。這是WPF應用程序。 – user3595338

回答

0

裹在一個新的線程代碼:

Thread thread = new Thread(() => 
{ 
    ManagementObjectSearcher theSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive"); 
    foreach (ManagementObject currentObject in theSearcher.Get()) 
    { 
     Debug.WriteLine("Device present: " + currentObject);   
     ManagementObject theSerialNumberObjectQuery = new ManagementObject("Win32_PhysicalMedia.Tag='" + currentObject["DeviceID"] + "'"); 
     serial = theSerialNumberObjectQuery["SerialNumber"].ToString(); 
    } 
}); 
thread.Start(); 
thread.Join(); //wait for the thread to finish