该应用程序调用了一个为不同线程编组的接口。获取USB_Hub列表时

时间:2017-04-05 18:13:20

标签: c# wpf

我使用下面的代码获取USB设备列表。但是当我在没有调试的情况下运行它会显示错误:

该应用程序调用了一个为不同线程编组的接口。

但是当我使用调试运行应用程序时,它工作正常。我在单独的类库项目中使用此函数并在WPF表单上调用它。

public static List<USBDeviceInfo> GetUSBDevices()
    {
        List<USBDeviceInfo> devices = new List<USBDeviceInfo>();
        ManagementScope scope = new ManagementScope("\\\\.\\ROOT\\cimv2");
        ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_USBHub");
        try
        {
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
            ManagementObjectCollection queryCollection = searcher.Get();
            //ManagementObjectCollection collection;
            //using (var searcher = new ManagementObjectSearcher(@"Select * From Win32_USBHub"))
            //var searcher = new ManagementObjectSearcher(@"Select * From Win32_USBHub");
            //collection = searcher.Get();

            foreach (ManagementObject device in queryCollection)
            {
                devices.Add(new USBDeviceInfo(
                (string)device.GetPropertyValue("DeviceID"),
                (string)device.GetPropertyValue("PNPDeviceID"),
                (string)device.GetPropertyValue("Description"),
                (string)device.GetPropertyValue("Name")
                ));
            }
        }
        catch (ManagementException MEEx)
        {
            throw MEEx;
        }
        catch(COMException COMEx)
        {
            throw COMEx;
        }
        finally
        {

        }
        //collection.Dispose();
        return devices;
    }

    public class USBDeviceInfo
    {
        public USBDeviceInfo(string deviceID, string pnpDeviceID, string description, string name)
        {
            this.DeviceID = deviceID;
            this.PnpDeviceID = pnpDeviceID;
            this.Description = description;
            this.Name = name;
        }
        public string DeviceID { get; private set; }
        public string PnpDeviceID { get; private set; }
        public string Description { get; private set; }
        public string Name { get; private set; }

    }

1 个答案:

答案 0 :(得分:0)

我用过

Application.Current.Dispatcher.InvokeAsync(new Action(() => {     IDALUsbDetection.GetUSBDevices(); }));

调用函数。工作得很好。