【问题标题】:How to make forward-only, read-only WMI queries in C#?如何在 C# 中进行只进、只读的 WMI 查询?
【发布时间】:2009-06-11 01:11:09
【问题描述】:

一位同事告诉我,如果我的 WMI 系统信息收集查询是只进和/或只读的,它们会更快。这就说得通了。但是我该怎么做呢?

【问题讨论】:

    标签: c# .net wmi


    【解决方案1】:

    您需要使用 EnumerationOptions 类并将其 Rewindable 属性设置为 false。这是一个例子:

    using System;
    using System.Management;
    
    namespace WmiTest
    {
        class Program
        {
            static void Main()
            {
                EnumerationOptions options = new EnumerationOptions();
                options.Rewindable = false;
                options.ReturnImmediately = true;
    
                string query = "Select * From Win32_Process";
    
                ManagementObjectSearcher searcher =
                    new ManagementObjectSearcher(@"root\cimv2", query, options);
    
                ManagementObjectCollection processes = searcher.Get();
    
                foreach (ManagementObject process in processes)
                {
                    Console.WriteLine(process["Name"]);
                }
    
                // Uncomment any of these
                // and you will get an exception:
    
                //Console.WriteLine(processes.Count);
    
                /*
                foreach (ManagementObject process in processes)
                {
                    Console.WriteLine(process["Name"]);
                }
                */
            }
        }
    }
    

    除非您使用它来枚举具有大量实例的类(如 Cim_DataFile),否则您不会看到任何性能改进,并且您只能枚举返回的 ManagementObjectCollection 一次。您也将无法使用 ManagementObjectCollection.Count 等。 至于只读查询,我不知道怎么做。

    【讨论】:

      【解决方案2】:

      您的同事一定是打算将 半同步 方法调用与只进枚举器一起使用。在半同步模式下,WMI 方法调用立即返回,对象在后台检索并在创建后按需返回。另外,当使用半同步模式检索大量实例时,建议获取只进枚举器以提高性能。这个MSDN article解释了这些特性。

      正如 Uros 指出的那样,要在半同步模式下获取只进枚举器,您需要使用 EnumerationOptions 类实例,并将 ReturnImmediately 属性设置为 true 并将 Rewindable 属性设置为 @ 987654326@,例如:

      EnumerationOptions opt = new EnumerationOptions();
      opt.ReturnImmediately = true;
      opt.Rewindable = false;
      
      ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query, opt);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-09-04
        • 2013-01-04
        • 1970-01-01
        • 2016-03-04
        • 2013-06-24
        • 2022-11-25
        • 2015-01-18
        相关资源
        最近更新 更多