C# Winform时时检测电脑的CPU使用率和物理内存使用率
时间: 2024-05-13 15:18:11 浏览: 19
你可以使用PerformanceCounter类来实现这个功能。以下是一个简单的示例代码:
```csharp
using System.Diagnostics;
...
// 创建PerformanceCounter对象
var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
var memCounter = new PerformanceCounter("Memory", "Available MBytes");
// 获取CPU和内存使用率
var cpuUsage = (int)cpuCounter.NextValue();
var memUsage = (int)memCounter.NextValue();
// 输出使用率
Console.WriteLine($"CPU使用率:{cpuUsage}%");
Console.WriteLine($"内存使用率:{100 - memUsage}%");
```
这段代码创建了两个`PerformanceCounter`对象,分别用于获取CPU使用率和可用内存大小。然后通过调用`NextValue`方法获取当前的使用率值,并将其输出到控制台上。你可以根据自己的需要将这些值用于其他用途。
需要注意的是,CPU使用率的计算依赖于计算时间间隔的设置,即在两次调用`NextValue`方法之间的时间间隔。如果时间间隔太短,会导致计算出的使用率值不准确。因此,你可以使用`Thread.Sleep`方法来等待一段时间再重新获取使用率值。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)