如何在C#中获取或使用内存

问题描述 投票:123回答:6

如何获取应用程序使用的可用RAM或内存?

c# memory-management
6个回答
159
投票

您可以使用:

Process proc = Process.GetCurrentProcess();

要获得当前流程并使用:

proc.PrivateMemorySize64;

获取私有内存使用情况。有关更多信息,请查看this link


37
投票

您可能想要检查GC.GetTotalMemory方法。

它检索当前认为由垃圾收集器分配的字节数。


23
投票

System.EnvironmentWorkingSet-一个64位有符号整数,包含映射到进程上下文的物理内存的字节数。

如果你想要很多细节,那就有System.Diagnostics.PerformanceCounter,但设置起来会有点费劲。


8
投票

查看here了解详情。

private PerformanceCounter cpuCounter;
private PerformanceCounter ramCounter;
public Form1()
{
    InitializeComponent();
    InitialiseCPUCounter();
    InitializeRAMCounter();
    updateTimer.Start();
}

private void updateTimer_Tick(object sender, EventArgs e)
{
    this.textBox1.Text = "CPU Usage: " +
    Convert.ToInt32(cpuCounter.NextValue()).ToString() +
    "%";

    this.textBox2.Text = Convert.ToInt32(ramCounter.NextValue()).ToString()+"Mb";
}

private void Form1_Load(object sender, EventArgs e)
{
}

private void InitialiseCPUCounter()
{
    cpuCounter = new PerformanceCounter(
    "Processor",
    "% Processor Time",
    "_Total",
    true
    );
}

private void InitializeRAMCounter()
{
    ramCounter = new PerformanceCounter("Memory", "Available MBytes", true);

}

如果你得到0的值,它需要两次调用NextValue()。然后它给出了CPU使用率的实际值。查看更多详情here


2
投票

除了@JesperFyhrKnudsen的答案和@MathiasLykkegaardLorenzen的评论之外,你最好使用dispose返回的Process

所以,为了处理Process,你可以将它包装在using范围内或在返回的进程上调用Disposeproc变量)。

  1. using范围: var memory = 0.0; using (Process proc = Process.GetCurrentProcess()) { // The proc.PrivateMemorySize64 will returns the private memory usage in byte. // Would like to Convert it to Megabyte? divide it by 1e+6 memory = proc.PrivateMemorySize64 / 1e+6; }
  2. Dispose方法: var memory = 0.0; Process proc = Process.GetCurrentProcess(); memory = Math.Round(proc.PrivateMemorySize64 / 1e+6, 2); proc.Dispose();

现在你可以使用转换为兆字节的memory变量。


1
投票

对于完整的系统,您可以添加Microsoft.VisualBasic Framework作为参考;

 Console.WriteLine("You have {0} bytes of RAM",
        new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory);
        Console.ReadLine();
© www.soinside.com 2019 - 2024. All rights reserved.