c# - 如何在 C# 中进行只进、只读的 WMI 查询?

标签 c# .net wmi

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

最佳答案

您需要使用 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 等。 至于只读查询,我不确定如何进行。

关于c# - 如何在 C# 中进行只进、只读的 WMI 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/978862/

相关文章:

powershell - 使用 WMI 获取 IIS6 网站的所有虚拟目录

c# - JavaScript 哈希和等效的 .NET 算法

c# - 类内部结构

c# - 无法加载文件或程序集“System.Security.Cryptography.Algorithms,版本 = 4.1.0.0

.net - Rhino 模拟错误 : Previous method 'IEnumerator.MoveNext();' requires a return value or an exception to throw

c# - Win32_ProcessStartTrace 的 ManagementEventWatcher 在 Win 8.1 中不再工作

python - 在 Python 中禁用注册表重定向到 Wow6432Node

c# - 如何使用不是第二个对象的主键的键创建导航属性?

c# - 如何从 .Net Core 连接到 Oracle 数据库连接

c# - MySQL 连接器 v.6.3.6 .NET 中 GUID 类型的问题