一位同事告诉我,如果我的WMI系统信息收集查询只是前向和/或只读,那么它们会更快.那讲得通.但是我该怎么办呢?
小智 5
您需要使用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"]);
}
*/
}
}
}
Run Code Online (Sandbox Code Playgroud)
除非您使用它枚举具有大量实例的类(如Cim_DataFile),否则您将看不到任何性能改进,并且您将仅枚举返回的ManagementObjectCollection一次.您也将无法使用ManagementObjectCollection.Count等.至于只读查询,我不知道如何制作它们.