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

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

这段代码抛出了以下异常

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

我放置了

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

在 LoadDevices 方法的开头,我发现它总是从同一个线程(1)调用。你能解释一下这里发生了什么,并且如何解决这个错误吗?

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

谢谢。

0

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

public async SomeMethod()
{
    await CoreWindow.GetForCurrentThread().Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
        {
             //   Your code here...
        });
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接