一位同事告诉我,如果我的 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/