Let's talk about how to obtain the machine's memory and CPU information.
Recently, a project was created to obtain the CPU and memory usage of the machine. It took some time to search online and I did some tests myself. To sum up, there are basically two methods: one is WMI and the other is Performance counter.
1. use WMI to create connection to the computer passing username and password. once the connection is created, query the CPU & memory by passing the query, similar as SQL. this way can get CPU & memory for remote PC and local PC. for example:
System. Management. ConnectionOptions Conn = new ConnectionOptions ();
Conn. Username = mpusername;
Conn. Password = mppwd;
String scopestring = "//" + mpserver + "/root/cimv2 ";
System. Management. ManagementScope MS = new ManagementScope (scopestring );
Ms. Connect ();
Mos. Scope = MS;
ObjectQuery oq = new ObjectQuery ();
Oq. QueryString = "select * from Win32_Processor ";
Mos. Query = oq;
ManagementObjectCollection moc = mos. Get ();
The Memory takes a lot of time. The previous object has expired and cannot be used. Finally, find the class "Win32_PerfRawData_PerfOS_Memory"
ManagementObjectCollection mcr = mcp. getQueryResult ("select * from Win32_ComputerSystem ");
Foreach (ManagementObject mo in mcr)
{
If (mo ["TotalPhysicalMemory"]! = Null)
{
Totalm = long. Parse (mo ["TotalPhysicalMemory"]. ToString ());
}
}
ManagementObjectCollection moc = mcp. getQueryResult ("select * from Win32_PerfRawData_PerfOS_Memory ");
Foreach (ManagementObject mo in moc)
{
String avilable = mo. GetPropertyValue ("AvailableBytes"). ToString ();
Avilablem = long. Parse (avilable );
}
2. Get local server's CPU and momory information passing the WMI classes, such as "Win32_Processor", "Win32_OperatingSystem"
ManagementClass mc = new ManagementClass ("Win32_OperatingSystem ");
ManagementObjectCollection moc = mc. GetInstances ();
3. use performance counter to get performance data passing the performance counter name, such as monitor. performanceCounterFun ("Processor", "_ Total", "% Processor Time "). normally we shoud get performance counter data several times, then use the average values.
Although this is relatively simple, I still want to record it and hope it will be useful to everyone!