I want implement a system that monitors currently running processes. The system get information about high load (CPU, Memory, etc.). I investigate two namespaces. It is System.Diagnostics and System.Management. First, I wrote a class to display the names, IDs and CPU Load of all running processes.
class Program
{
static void Main()
{
Console.WriteLine("--------------using System.Diagnostics---------------------");
SysDi();
Console.WriteLine("----using System.Diagnostics CPU load always zero----------");
//Here CPU load always zero
SysDiCpuZero();
Console.WriteLine("--------------using System.Management---------------------");
Vmi();
}
static void Vmi()
{
try
{
var searcher = new ManagementObjectSearcher("root\\CIMV2",
"SELECT * FROM Win32_PerfFormattedData_PerfProc_Process");
foreach (var queryObj in searcher.Get())
{
Console.WriteLine($"Process: {queryObj["Name"]} " +
$"ID: {queryObj["CreatingProcessID"]} " +
$"CPU load: {queryObj["PercentProcessorTime"]}");
}
}
catch (ManagementException e)
{
Console.WriteLine("An error occurred while querying for WMI data: " + e.Message);
}
}
static void SysDi()
{
var processlist = Process.GetProcesses();
var counters = new List<PerformanceCounter>();
foreach (var theprocess in processlist)
{
var counter = new PerformanceCounter("Process", "% Processor Time", theprocess.ProcessName);
counter.NextValue();
counters.Add(counter);
}
var i = 0;
Thread.Sleep(10);
foreach (var counter in counters)
{
Console.WriteLine($"Process: {processlist[i].ProcessName} " +
$"ID: {processlist[i].Id} " +
$"CPU load: {Math.Round(counter.NextValue(), 5)}");
++i;
}
}
static void SysDiCpuZero()
{
var processlist = Process.GetProcesses();
foreach (var theprocess in processlist)
{
var counter = new PerformanceCounter("Process", "% Processor Time", theprocess.ProcessName);
counter.NextValue();
Console.WriteLine($"Process: {theprocess.ProcessName} " +
$"ID: {theprocess.Id} " +
$"CPU load: {Math.Round(counter.NextValue(), 5)}");
}
}
}
Also, I noticed that in different namespaces the same properties have different values. Also, System.Diagnostic faster than System.Management but method SysDi() with CPU loading data looks like unclear.
What is better to use in my case? What criteria should I follow to choose?