Reputation:
How can I get the available RAM or memory used by the application?
Upvotes: 184
Views: 242322
Reputation: 7917
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.
Upvotes: 218
Reputation: 2890
System.Environment has WorkingSet- a 64-bit signed integer containing the number of bytes of physical memory mapped to the process context.
In .NET Core 3.0 and later (aka .NET 5 and later), you can use GC.GetGCMemoryInfo
to get information about memory used by the GC heap and how much memory the GC thinks is available. .NET internally uses this data to calculate memory pressure. The memory pressure is used to decide when to trim the System.Buffers.ArrayPool.
Upvotes: 37
Reputation: 2271
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).
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 2^20
memory = proc.PrivateMemorySize64 / (1024*1024);
}
Or Dispose
method:
var memory = 0.0;
Process proc = Process.GetCurrentProcess();
memory = Math.Round(proc.PrivateMemorySize64 / (1024*1024), 2);
proc.Dispose();
Now you could use the memory
variable which is converted to Megabyte.
Upvotes: 24
Reputation: 4933
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.
Upvotes: 14
Reputation: 5254
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();
Upvotes: 0
Reputation: 827158
You might want to check the GC.GetTotalMemory method.
It retrieves the number of bytes currently thought to be allocated by the garbage collector.
Upvotes: 46