I want to get multiple details from a few servers in my environment.
This code is working, but is this code a good way to get the details ?
Is it ok to call "new ManagementObjectSearcher" at every request ?
ManagementObjectSearcher cpuUsage = new ManagementObjectSearcher
("\\\\" + strComputer + "\\root\\CIMV2",
"SELECT * FROM Win32_Processor");
foreach (ManagementObject queryObj in cpuUsage.Get())
{
Console.WriteLine("LoadPercentage: {0}", queryObj["LoadPercentage"]);
}
ManagementObjectSearcher totalRAM = new ManagementObjectSearcher
("\\\\" + strComputer + "\\root\\CIMV2",
"SELECT * FROM Win32_ComputerSystem");
foreach (ManagementObject queryObj in totalRAM.Get())
{
Console.WriteLine("TotalPhysicalMemory: {0}", queryObj["TotalPhysicalMemory"]);
}
ManagementObjectSearcher freeRAM = new ManagementObjectSearcher
("\\\\" + strComputer + "\\root\\CIMV2",
"SELECT * FROM Win32_PerfFormattedData_PerfOS_Memory");
foreach (ManagementObject queryObj in freeRAM.Get())
{
Console.WriteLine("AvailableMBytes: {0}", queryObj["AvailableMBytes"]);
}
I have done something similar. My application is longer running so I keep one ManagementScope
per machine and one ManagementObjectSearcher
per query per machine. I only dispose of these objects when if I get any error during a query.