如何在C#中正确使用性能计数器或进程类来获取当前进程的内存使用情况

本文关键字:进程 获取 情况 用情 内存 性能计数器 | 更新日期: 2023-09-27 18:21:04

根据如何使用.NET PerformanceCounter跟踪每个进程的内存和CPU使用情况?PerformanceCounter应该给我给定进程的内存使用次数。

根据MSDN,Process实例可能也会给我或多或少相同的数字。

为了验证我的假设,我编写了以下代码:

class Program
{
    static Process process = Process.GetCurrentProcess();
    static PerformanceCounter privateBytesCounter = new PerformanceCounter("Process", "Private Bytes", process.ProcessName);
    static PerformanceCounter workingSetCounter = new PerformanceCounter("Process", "Working Set", process.ProcessName);
    static void Main(string[] args)
    {

        GetMeasure();
        Console.WriteLine("'nPress enter to allocate great amount of memory");
        Console.ReadLine();
        int[] arr = new int[10000000];
        for (int i = 0; i < arr.Length; i++)
        {
            arr[i] = i;
        }
        GetMeasure();
        privateBytesCounter.Dispose();
        workingSetCounter.Dispose();
        Console.ReadKey();
    }
    private static void GetMeasure()
    {
        Console.WriteLine("{0,38} {1,20}", "Private bytes", "working set");
        Console.WriteLine("process data{0,23} {1,20}", process.PrivateMemorySize64 / 1024, process.WorkingSet64 / 1024);
        Console.WriteLine("PerformanceCounter data{0,12} {1,20}", privateBytesCounter.NextValue() / 1024, workingSetCounter.NextValue() / 1024);
    }
}

输出看起来像

                         Private bytes          working set
process data                  22880                17516
PerformanceCounter data       21608                15608
Press enter to allocate great amount of memory
                         Private bytes          working set
process data                  22880                17516
PerformanceCounter data       21608                15608

完全一样!相比之下,Process Explorer中显示的私有字节从32732增加到63620。

那么我是不是做错了什么?

如何在C#中正确使用性能计数器或进程类来获取当前进程的内存使用情况

您必须告诉您的process实例它应该刷新其缓存的数据。并非每次出于性能目的访问属性时都会收集数据。您必须手动要求更新数据。

private static void GetMeasure()
{
    process.Refresh();  // Updates process information
    Console.WriteLine("{0,38} {1,20}", "Private bytes", "working set");
    Console.WriteLine("process data{0,23} {1,20}", process.PrivateMemorySize64 / 1024, process.WorkingSet64 / 1024);
    Console.WriteLine("PerformanceCounter data{0,12} {1,20}", privateBytesCounter.NextValue() / 1024, workingSetCounter.NextValue() / 1024);
}

这是给你的process的。对于性能计数器,NextValue()应该每次都检索一个新的新数据,所以我无法解释为什么它不在您的机器上。对我来说效果很好。

编辑

添加了process.Refresh()后,我得到的是:

                         Private bytes          working set
process data                  25596                22932
PerformanceCounter data       26172                23600
Press enter to allocate great amount of memory
                         Private bytes          working set
process data                  65704                61848
PerformanceCounter data       65828                61880

注意:我的内存探查器(.NET内存探查器)显示Process.Refresh()会临时分配大量内存,所以如果您使用计时器定期读取性能计数器,请记住这一点。