How to get memory available or used in C#

2019-01-01 12:47发布

问题:

How can I get the available RAM or memory used by the application?

回答1:

You can use:

Process proc = Process.GetCurrentProcess();

To get the current process and use:

proc.PrivateMemorySize64;

To get the private memory usage. For more information look at this link.



回答2:

You might want to check the GC.GetTotalMemory method.

It retrieves the number of bytes currently thought to be allocated by the garbage collector.



回答3:

System.Environment has WorkingSet. If you want a lot of details there is System.Diagnostics.PerformanceCounter, but it will be a bit more effort to setup.



回答4:

Look here for details.

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);

}

If you get value as 0 it need to call NextValue() twice. Then it gives the actual value of CPU usage. See more details here.



回答5:

In addition to @JesperFyhrKnudsen\'s answer and @MathiasLykkegaardLorenzen\'s comment, you\'d better dispose the returned Process after using it.

So, In order to dispose the Process, you could wrap it in a using scope or calling Dispose on the returned process (proc variable).

  1. using scope:

    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. Or Dispose method:

    var memory = 0.0;
    Process proc = Process.GetCurrentProcess();
    memory = Math.Round(proc.PrivateMemorySize64 / 1e+6, 2);
    proc.Dispose();
    

Now you could use the memory variable which is converted to Megabyte.



回答6:

For the complete system you can add the Microsoft.VisualBasic Framework as a reference;

 Console.WriteLine(\"You have {0} bytes of RAM\",
        new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory);
        Console.ReadLine();