C# Get used memory in %

前端 未结 4 1229

I\'ve created a performancecounter that can check the total memory usage in %, but the problem is that it doesn\'t give me the same value as in task manager shows me. for ex

4条回答
  •  臣服心动
    2020-12-07 21:07

    Performance counters is not good idea. Use this code to get % of memory usage from Task Manager

    var wmiObject = new ManagementObjectSearcher("select * from Win32_OperatingSystem");
    
    var memoryValues = wmiObject.Get().Cast().Select(mo => new {
        FreePhysicalMemory = Double.Parse(mo["FreePhysicalMemory"].ToString()),
        TotalVisibleMemorySize = Double.Parse(mo["TotalVisibleMemorySize"].ToString())
    }).FirstOrDefault();
    
    if (memoryValues != null) {
        var percent = ((memoryValues.TotalVisibleMemorySize - memoryValues.FreePhysicalMemory) / memoryValues.TotalVisibleMemorySize) * 100;
    }
    

提交回复
热议问题