我正在尝试在C#中模仿Windows 7任务管理器(仅限性能选项卡),虽然我设法获得了大多数值,但我无法获得物理内存的缓存和空闲字节值。我知道他们的意思是:
- 缓存是指最近用于系统资源的物理内存量。
- Free是当前未使用或不包含有用信息的内存量(与包含有用信息的缓存文件不同)。
但我的方法都没有产生任务管理器中显示的确切值。 e.g:
缓存:
PerformanceCounter PC4 = new PerformanceCounter();
PC4.CategoryName = "Memory";
PC4.CounterName = "Cache Bytes";
PC4.InstanceName = "";
Console.WriteLine((Int32)(PC4.NextValue() / (1024 * 1024)));
免
ObjectQuery wql = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(wql);
ManagementObjectCollection results = searcher.Get();
object ob = 0;
foreach (ManagementObject result in results)
{
ob = result["FreePhysicalMemory"];
}//returns physical memory's <i>Available</i> byte, NOT <i>Free</i>
有什么我想念的吗?
答案 0 :(得分:0)
您可以尝试查看System.Diagnostics.Process类。 我认为Process.PagedMemorySize是你感兴趣的。 以下代码示例将吐出一系列正在运行的进程及其mem用法:
Process[] processlist = Process.GetProcesses();
foreach(Process p in processlist){
Console.WriteLine(“Process: {0} ID: {1} MEM:{2}”, p.ProcessName, p.Id, theprocess.PagedMemorySize);
}
如果没有PagedMemorySize,可以试试VirtualMemorySize64
http://msdn.microsoft.com/en-us/library/system.diagnostics.process(v=vs.110).aspx
答案 1 :(得分:0)
您需要添加对Microsoft.VisualBasic的引用才能使用以下内容:
using System.Runtime.InteropServices;
using Microsoft.VisualBasic.Devices;
public class MemStat
{
public ulong Available { get; set; }
public ulong Total { get; set; }
public ulong PhysicalMemoryInUse { get; set; }
public ulong Free { get; set; }
public ulong Cached { get; set; }
public MemStat()
{
ObjectQuery wql = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(wql);
ManagementObjectCollection results = searcher.Get();
var Available = new ComputerInfo().AvailablePhysicalMemory;
this.Available = Available;
var Total = new ComputerInfo().TotalPhysicalMemory;
this.Total = Total;
var PhysicalMemoryInUse = Total - Available;
this.PhysicalMemoryInUse = PhysicalMemoryInUse;
Object Free = new object();
foreach (var result in results)
{
Free = result["FreePhysicalMemory"];
this.Free = ulong.Parse(Free.ToString());
}
var Cached = Total - PhysicalMemoryInUse - ulong.Parse(Free.ToString());
this.Cached = Cached;
}
然后像这样使用它:
ulong TotalMemory = new MemStat().Total;
ulong FreeMemory = new MemStat().Free;
Console.BackgroundColor = ConsoleColor.Blue;
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine(" **** MY WINDOWS PROGRAM **** ");
Console.WriteLine("" + (TotalMemory/1024) + "K RAM SYSTEM " + FreeMemory + " BYTES FREE");