c#在core6获取某个进程的每秒的内存使用率
时间: 2024-02-05 16:11:19 浏览: 22
可以使用System.Diagnostics命名空间中的Process类来获取进程的内存使用情况。下面是一个获取某个进程每秒内存使用率的示例代码:
```csharp
using System;
using System.Diagnostics;
public class MemoryUsageMonitor
{
private PerformanceCounter _memoryCounter;
private Process _process;
public MemoryUsageMonitor(int processId)
{
_process = Process.GetProcessById(processId);
_memoryCounter = new PerformanceCounter("Process", "Working Set - Private", _process.ProcessName);
}
public float GetMemoryUsageMB()
{
return _memoryCounter.NextValue() / 1024 / 1024;
}
}
// 在需要监控的代码中使用
var monitor = new MemoryUsageMonitor(processId);
while (true)
{
Console.WriteLine($"Memory usage: {monitor.GetMemoryUsageMB()} MB");
System.Threading.Thread.Sleep(1000);
}
```
其中,`PerformanceCounter`类可以用来获取指定进程的内存使用情况,`NextValue()`方法可以获取下一个计数器的值。在上面的示例中,我们使用了"Working Set - Private"计数器来获取进程的私有内存使用量,并将结果转换为MB。该示例程序每秒钟输出一次内存使用量。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)