【问题标题】:How to get CPU Usage and Virtual Memory for a process in .Net Core?如何获取 .Net Core 中进程的 CPU 使用率和虚拟内存?
【发布时间】:2019-01-14 09:26:00
【问题描述】:

在 .NET Core 中,如何获取给定进程的 CPU 使用率和虚拟内存?

Google 搜索结果显示 PerformanceCounter 和 DriverInfo 类可以完成这项工作。但是,PerformanceCounter 和 DriverInfo 类在 .NET Core 中不可用。

stackoverflow 中有一篇关于这个问题的帖子:How to get the current CPU/RAM/Disk usage in a C# web application using .NET CORE?

但它只针对: -当前进程的CPU使用率:

    var proc = Process.GetCurrentProcess();

我已获得进程(使用 ProcessID 整数格式)。如何在 .NET Core 中获取该特定进程的 CPU 使用率和虚拟内存?

【问题讨论】:

  • 听起来 .Net Core 目前是满足您要求的错误选择。为什么不直接使用 .Net 框架?
  • 我上面写的代码是针对.Net core的。不是 .Net 框架
  • 我知道...我的意思是,您为什么使用 .Net Core?您在 .Net Framework 上使用它是否有特定原因?
  • @JamieRees,上述功能需要在 .Net Core 中运行,因为该项目需要在 Windows、Linux、macOS 和 Docker 的 Web 应用程序和服务中运行。
  • 这仍然可以在.Net Framework中使用Mono完成

标签: c# .net-core


【解决方案1】:

你可以在System.Diagnostics.PerformanceCounterpackage中使用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);

【讨论】:

  • Linux 不支持 PerformanceCounter
【解决方案2】:

我刚刚在 google 中输入了“get all processes in c#”并找到了这个:

        Process[] processlist = Process.GetProcesses();

        foreach (Process theprocess in processlist)
        {
        }

我在 asp.net core 2.2 中快速进行了测试,使用 System.Diagnostics 可以正常工作; 不过我用windows 10 pro来测试一下。所以我不知道它是否适用于其他操作系统。

来源:https://www.howtogeek.com/howto/programming/get-a-list-of-running-processes-in-c/

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2021-10-13
  • 1970-01-01
  • 2011-09-11
  • 2021-03-22
  • 1970-01-01
  • 2015-07-22
  • 2017-12-29
  • 1970-01-01
相关资源
最近更新 更多