在.NET Core中,如何获取给定进程的CPU使用率和虚拟内存?
谷歌搜索结果显示,PerformanceCounter和DriverInfo类可以完成这项工作。但是,PerformanceCounter 和 DriverInfo 类在 .NET Core 中不可用。
在stackoverflow中有一篇关于这个问题的文章:如何使用.NET CORE获取C# Web应用程序中的当前CPU/RAM/磁盘使用情况?
但是,它仅解决:-当前进程的 CPU 使用率:
var proc = Process.GetCurrentProcess();
我已经得到了进程(使用进程ID整数格式)。如何在 .NET Core 中获取该特定进程的 CPU 使用率和虚拟内存?
System.Diagnostics.PerformanceCounter
包中使用PerformnceCounter
例如,下一个代码将为您提供处理器总使用率百分比
var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total", true);
var value = cpuCounter.NextValue();
// In most cases you need to call .NextValue() twice
if (Math.Abs(value) <= 0.00)
value = cpuCounter.NextValue();
Console.WriteLine(value);
您可以使用这样的东西来获取 netcore 进程内存:
var process = Process.GetCurrentProcess();
var workingSet64 = process.WorkingSet64;
var privateMemorySize64 = process.PrivateMemorySize64;
var virtualMemorySize64 = process.VirtualMemorySize64;
对于 CPU 使用率:
private static DateTime? _previousCpuStartTime = null;
private static TimeSpan? _previousTotalProcessorTime = null;
private static double GetCpuUsageForProcess()
{
var currentCpuStartTime = DateTime.UtcNow;
var currentCpuUsage = Process.GetCurrentProcess().TotalProcessorTime;
// If no start time set then set to now
if (!_previousCpuStartTime.HasValue)
{
_previousCpuStartTime = currentCpuStartTime;
_previousTotalProcessorTime = currentCpuUsage;
}
var cpuUsedMs = (currentCpuUsage - _previousTotalProcessorTime.Value).TotalMilliseconds;
var totalMsPassed = (currentCpuStartTime - _previousCpuStartTime.Value).TotalMilliseconds;
var cpuUsageTotal = cpuUsedMs / (Environment.ProcessorCount * totalMsPassed);
// Set previous times.
_previousCpuStartTime = currentCpuStartTime;
_previousTotalProcessorTime = currentCpuUsage;
return cpuUsageTotal * 100.0;
}
刚刚在谷歌中输入了"获取 c# 中的所有进程",发现这个:
Process[] processlist = Process.GetProcesses();
foreach (Process theprocess in processlist)
{
}
我在 asp.net Core 2.2 中快速进行了测试,它使用系统诊断工作正常;但是我使用Windows 10 Pro对其进行了测试。所以我不知道它是否适用于其他操作系统。
来源: https://www.howtogeek.com/howto/programming/get-a-list-of-running-processes-in-c/