如何让只进,只读在C#WMI查询?让只进、WMI

2023-09-05 02:45:21 作者:刀伐戏子

我已经告诉一个同事说,如果我的WMI的系统收集信息查询是只进和/或只读,他们会非常快。这就说得通了。但是,我怎么办呢?

I've been told by a coworker that if my WMI system information gathering queries are forward-only and/or read-only, they'll be quite faster. That makes sense. But how do I do it?

推荐答案

您需要使用EnumerationOptions类并将其rewindable的属性设置为false。下面是一个例子:

You need to use EnumerationOptions class and set its Rewindable property to false. Here is an example:

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等 对于只读查询,我不知道如何使这些。

You won't see any performance improvement unless you use it to enumerate a class with a large number of instances (like Cim_DataFile) and you will get to enumerate the returned ManagementObjectCollection only once. You also won't be able to use ManagementObjectCollection.Count, etc. As for read-only queries, I'm not sure how to make those.