How to get memory available or used in C#
Solution 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.
Solution 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.
Solution 3:
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.
Solution 4:
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.