C# 如何跟踪进程内存和CPU?
获取进程的CPU和内存使用率的过程是什么?我必须传递什么值C# 如何跟踪进程内存和CPU?,c#,asp.net-mvc,performancecounter,C#,Asp.net Mvc,Performancecounter,获取进程的CPU和内存使用率的过程是什么?我必须传递什么值 Process p = new Process(); PerformanceCounter ramCounter = new PerformanceCounter("Process", "Working Set", p.ProcessName); PerformanceCounter cpuCounter = new PerformanceCounter("Process", "% Processor Time", p.ProcessN
Process p = new Process();
PerformanceCounter ramCounter = new PerformanceCounter("Process", "Working Set", p.ProcessName);
PerformanceCounter cpuCounter = new PerformanceCounter("Process", "% Processor Time", p.ProcessName);
while (true)
{
Thread.Sleep(500);
double ram = ramCounter.NextValue();
double cpu = cpuCounter.NextValue();
Console.WriteLine("RAM: " + (ram / 1024 / 1024) + " MB; CPU: " + (cpu) + " %");
Console.ReadLine();
}
对于
过程
,可以使用静态方法。结果进入性能计数器
在以下控制器中,PerformanceCounter创建一次,然后重新使用。计时器保证在第一次调用之前已经过了500毫秒
public class PerformanceController : Controller
{
static PerformanceCounter ramCounter;
static PerformanceCounter cpuCounter;
static Timer timer;
static ManualResetEvent waiter = new ManualResetEvent(false);
static Performance lastMeasure = new Performance(); // the Model (in Mvc)
static PerformanceController()
{
// Get the current process
using (var p = Process.GetCurrentProcess())
{
ramCounter = new PerformanceCounter("Process", "Working Set", p.ProcessName);
cpuCounter = new PerformanceCounter("Process", "% Processor Time", p.ProcessName);
}
// make sure some time has passed before first NextValue call
timer = new Timer(s =>
{
waiter.Set();
}, null, 500, Timeout.Infinite);
// clean-up
AppDomain.CurrentDomain.DomainUnload += (s, e) => {
var time = (IDisposable)timer;
if (time != null) time.Dispose();
var wait = (IDisposable)waiter;
if (wait != null) wait.Dispose();
var rc = (IDisposable)ramCounter;
if (rc != null) rc.Dispose();
var cc = (IDisposable)cpuCounter;
if (cc != null) cc.Dispose();
};
}
private static Performance GetReading()
{
// wait for the first reading
waiter.WaitOne();
// maybe cache its values for a few seconds
lastMeasure.Cpu = cpuCounter.NextValue();
lastMeasure.Ram = ramCounter.NextValue();
return lastMeasure;
}
//
// GET: /Performance/
public ActionResult Index()
{
return View(GetReading());
}
}
性能模型非常简单:
public class Performance
{
public double Ram { get; set; }
public double Cpu { get; set; }
}
下面的视图完成了实现
@model mvcapapplication1.Models.Performance
@{
ViewBag.Title=“Index”;
}
指数
Ram@Model.Ram
Cpu@Model.Cpu
@CodeCaster,您的编辑确实改变了问题的意图,获取控制台应用程序的性能与获取MVC应用程序的性能非常不同,而问题的编写方式使其看起来像OP现在希望它用于控制台应用程序,而不是原始标记和标题所指示的那样。@Scott OP不能正确表达自己不是我的问题。在我看来,在标题中说“MVC”并应用“model view controller”标记并不意味着“为我将此控制台应用程序代码翻译为MVC”。如果有,OP可以自由地将该短语编辑到问题中。@Scott尽管如此,我已经应用了“asp.net mvc”标记,因为现有的答案现在假定是这样的。(同样,我认为,如果有人要回答某个问题,他们应该对其进行编辑,以使其更具可读性)。下次从答案(或问题)复制代码时,请确保链接到该答案并给出适当的属性: