Recently, a project has been done to get the CPU and memory usage of the machine. Spent some time searching the internet and doing some tests. summed up, basically 2 ways: one is to use WMI (2 kinds), the other is to use 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 is the 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 ();
Memory this piece spent more time, before the object has expired, can not be used, and finally found this 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_operatingsyste M
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 these are relatively simple, but I still want to record it, I hope to be useful to everyone!