这个能应用才timer里面吗
时间: 2023-08-07 10:19:13 浏览: 43
是的,您可以将上述代码放在`System.Timers.Timer`的回调函数中,以实现定时获取CPU占用率的功能。以下是一个简单的示例代码:
```csharp
using System.Diagnostics;
using System.Timers;
namespace GetCPUUsage
{
class Program
{
static void Main(string[] args)
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 1000;
timer.Elapsed += OnTimerElapsed;
timer.Start();
Console.ReadLine();
}
static void OnTimerElapsed(Object source, ElapsedEventArgs e)
{
PerformanceCounter cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
float cpuUsage = cpuCounter.NextValue();
Console.WriteLine("CPU Usage: " + cpuUsage + " %");
}
}
}
```
该代码将每秒输出CPU的占用率。您可以通过修改`timer.Interval`的值来调整输出频率。