我正在使用 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) 调用。您能否解释一下这里发生了什么以及如何摆脱这个错误?