5

我正在使用 WMI 来查询设备。插入或移除新设备时,我需要更新 UI(以使设备列表保持最新)。

private void LoadDevices()
{
    using (ManagementClass devices = new ManagementClass("Win32_Diskdrive"))
    {
        foreach (ManagementObject mgmtObject in devices.GetInstances())
        {
            foreach (ManagementObject partitionObject in mgmtObject.GetRelated("Win32_DiskPartition"))
            {
                foreach (ManagementBaseObject diskObject in partitionObject.GetRelated("Win32_LogicalDisk"))
                {
                    trvDevices.Nodes.Add( ... );
                }
            }
        }
    }
}

protected override void WndProc(ref Message m)
{
    const int WM_DEVICECHANGE = 0x0219;
    const int DBT_DEVICEARRIVAL = 0x8000;
    const int DBT_DEVICEREMOVECOMPLETE = 0x8004;
    switch (m.Msg)
    {
        // Handle device change events sent to the window
        case WM_DEVICECHANGE:
            // Check whether this is device insertion or removal event
            if (
                (int)m.WParam == DBT_DEVICEARRIVAL ||
                (int)m.WParam == DBT_DEVICEREMOVECOMPLETE)
        {
            LoadDevices();
        }

        break;
    }

    // Call base window message handler
    base.WndProc(ref m);
}

此代码引发异常并显示以下文本

The application called an interface that was marshalled for a different thread.

我放

MessageBox.Show(Thread.CurrentThread.ManagedThreadId.ToString());

在 LoadDevices 方法的开头,我看到它总是从同一个线程 (1) 调用。您能否解释一下这里发生了什么以及如何摆脱这个错误?

4

2 回答 2

2

最后我使用新线程解决了它。我拆分了这个方法,所以现在我有GetDiskDevices()方法LoadDevices(List<Device>),我有InvokeLoadDevices()方法。

private void InvokeLoadDevices()
{
    // Get list of physical and logical devices
    List<PhysicalDevice> devices = GetDiskDevices();

    // Check if calling this method is not thread safe and calling Invoke is required
    if (trvDevices.InvokeRequired)
    {
        trvDevices.Invoke((MethodInvoker)(() => LoadDevices(devices)));
    }
    else
    {
        LoadDevices(devices);
    }
}

当我收到 DBT_DEVICEARRIVAL 或 DBT_DEVICEREMOVECOMPLETE 消息时,我调用

ThreadPool.QueueUserWorkItem(s => InvokeLoadDevices());

谢谢。

于 2012-09-03T12:29:25.823 回答
0

对于 w10 上的 UWP,您可以使用:

public async SomeMethod()
{
    await CoreWindow.GetForCurrentThread().Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
        {
             //   Your code here...
        });
}
于 2016-04-21T21:30:29.670 回答