C# 为什么此WMI查询在第二次调用时挂起?

C# 为什么此WMI查询在第二次调用时挂起?,c#,.net-2.0,wmi,freeze,wmi-query,C#,.net 2.0,Wmi,Freeze,Wmi Query,以下WMI查询在serverProtocolsManagement.Get处引发异常,因为sqlHost是预期的无效服务器名称。但是,如果我尝试使用相同的无效参数再次调用此代码,ManagementScope构造函数将无限期挂起—永远不会返回或抛出错误,只是挂起。对此有合理的解释吗 try { ManagementScope managementScope = new ManagementScope(@"\\" + sqlHost + @"\root\Microsoft\Sql

以下WMI查询在serverProtocolsManagement.Get处引发异常,因为sqlHost是预期的无效服务器名称。但是,如果我尝试使用相同的无效参数再次调用此代码,ManagementScope构造函数将无限期挂起—永远不会返回或抛出错误,只是挂起。对此有合理的解释吗

try {

        ManagementScope managementScope = new ManagementScope(@"\\" + sqlHost + @"\root\Microsoft\SqlServer\ComputerManagement");
        using (ManagementClass serverProtocolsManagement = new ManagementClass(managementScope, new ManagementPath("ServerNetworkProtocol"), null)) {

            serverProtocolsManagement.Get();

            using (ManagementObjectCollection protocols = serverProtocolsManagement.GetInstances()) {
                foreach (ManagementObject protocol in protocols ) {
                    protocol.Get();

                    if ((string)protocol.GetPropertyValue("ProtocolName") == "Tcp" &&
                        (string)protocol.GetPropertyValue("InstanceName") == sqlInstanceName) {

                        protocol.InvokeMethod("SetEnable", null);
                    }
                }
            }
        }
    } catch (COMException ex) {
        MessageBox.Show(ex.ToString());
    }
编辑:

我试图通过将ConnectionOptions对象传递给ManagementScope构造函数来处理不同的超时选项,但没有效果

编辑2:


我不知道为什么我没有想到这一点,尽管这仍然应该不是一个问题:我在调试时从VS中的即时窗口调用了这段代码。一定是出现了某种线程问题,因为一旦我将此代码链接到Windows窗体按钮,一切都正常工作。谢谢你的帮助

将ManagementClass构造函数与字符串范围而不是ManagementScope对象一起使用时,是否存在相同的问题


因此,跳过整个ManagementScope步骤

显然,在调试时从即时窗口运行WMI查询是不允许的。通过按按钮执行查询,解决了问题。

我尝试了您的建议,是的,我也遇到了同样的问题。使用ManagementObjectSearcher对象而不是ManagementClass对象也有同样的问题。非常奇怪。。。