How to get memory available or used in C#

2019-01-01 13:14发布

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

6条回答
ら面具成の殇う
2楼-- · 2019-01-01 13:30

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.

查看更多
牵手、夕阳
3楼-- · 2019-01-01 13:34

You might want to check the GC.GetTotalMemory method.

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

查看更多
谁念西风独自凉
4楼-- · 2019-01-01 13:36

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();
查看更多
浅入江南
5楼-- · 2019-01-01 13:39

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.

查看更多
笑指拈花
6楼-- · 2019-01-01 13:49

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.

查看更多
时光乱了年华
7楼-- · 2019-01-01 13:52

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.

查看更多
登录 后发表回答