C#使用PerformanceCounter查詢CPU與記憶體使用狀況

C#使用PerformanceCounter查詢CPU與記憶體使用狀況

最近有個需求是要監控多台windows電腦上的CPU和memory使用率。

PerformanceCounter example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System;
using System.Diagnostics;
using System.Threading;

namespace test
{
class Program
{
static PerformanceCounter cpu = new PerformanceCounter("Processor", "% Processor Time", "_Total");
static PerformanceCounter memory = new PerformanceCounter("Memory", "% Committed Bytes in Use");

static void Main(string[] args)
{
while (true)
{
Console.WriteLine("CPU: {0:n1}%", cpu.NextValue());
Console.WriteLine("Memory: {0:n0}%", memory.NextValue());
Thread.Sleep(1000);
}
}
}
}