我想实现一个监控当前正在运行的进程的系统。系统获取有关高负载(CPU、内存等)的信息。我调查了两个命名空间。它是 System.Diagnostics 和 System.Management。首先,我编写了一个类来显示所有正在运行的进程的名称、ID 和 CPU 负载。
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)}");
}
}
}
另外,我注意到在不同的命名空间中,相同的属性具有不同的值。此外,System.Diagnostic 比 System.Management 更快,但带有 CPU 加载数据的方法 SysDi() 看起来不清楚。
在我的情况下使用什么更好?我应该遵循什么标准来选择?