How to Get Memory Available or Used in C#

How to get memory available or used in C# .net core / .net standard

Here you can check how it is done in HealthChecks project. You can use Process class from System.Diagnostics namespace.

* EDIT *

System.Diagnostics.Process Nuget package might need to be added.

Only xxxx64 memory properties are supported in .NET Standard (for example PrivateMemorySize64 and not PrivateMemorySize).

How to get the size of available system memory?

Use Microsoft.VisualBasic.Devices.ComputerInfo.TotalPhysicalMemory.

Right-click your project, Add Reference, select Microsoft.VisualBasic.

Get Available Free RAM Memory C#

Try with this...

Include a reference to the Microsoft.VisualBasic dll:

using Microsoft.VisualBasic.Devices;

...and then update your label as follows:

lbl_Avilable_Memory.Text = new ComputerInfo().AvailablePhysicalMemory.ToString() + " bytes free";

...or...

lbl_Avilable_Memory.Text = (ComputerInfo().AvailablePhysicalMemory / 1048576) + "mb free";

Notes:

  1. Reference the AvailablePhysicalMemory property of the ComputerInfo class in preference over the TotalPhysicalMemory property you used previously.
  2. The getAvailableRAM() method isn't required. Replace the call in ram_timer_tick with lbl_Avilable_Memory.Text = (ComputerInfo().AvailablePhysicalMemory / 1048576) + "mb free";
  3. It's also worth considering that methods that begin with the word get are expected to return a value. If the method was to stay then I'd recommend renaming it to SetLbl_Avilable_Memory() instead.
  4. You have spelled the word available incorrectly in your label name.

How to get the amount of memory used by an application

You can use the following function (The true parameter tells the GC to perform a collection first):

long memory = GC.GetTotalMemory(true);

How do you get total amount of RAM the computer has?

The Windows API function GlobalMemoryStatusEx can be called with p/invoke:

  [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
private class MEMORYSTATUSEX
{
public uint dwLength;
public uint dwMemoryLoad;
public ulong ullTotalPhys;
public ulong ullAvailPhys;
public ulong ullTotalPageFile;
public ulong ullAvailPageFile;
public ulong ullTotalVirtual;
public ulong ullAvailVirtual;
public ulong ullAvailExtendedVirtual;
public MEMORYSTATUSEX()
{
this.dwLength = (uint)Marshal.SizeOf(typeof(NativeMethods.MEMORYSTATUSEX));
}
}


[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool GlobalMemoryStatusEx([In, Out] MEMORYSTATUSEX lpBuffer);

Then use like:

ulong installedMemory;
MEMORYSTATUSEX memStatus = new MEMORYSTATUSEX();
if( GlobalMemoryStatusEx( memStatus))
{
installedMemory = memStatus.ullTotalPhys;
}

Or you can use WMI (managed but slower) to query TotalPhysicalMemory in the Win32_ComputerSystem class.

C# Get used memory in %

You could use GetPerformanceInfo windows API, it shows exactly the same values as Windows Task Manager on Windows 7, here is the console application that get's available physical memory, you could easily get other information that GetPerformanceInfo returns, consult MSDN PERFORMANCE_INFORMATION structure documentation to see how to calculate value in MiB, basically all SIZE_T values are in pages, so you must multiply it with PageSize.

Update: I updated this code to show percentage, it's not optimal because it's calling GetPerformanceInfo two times, but I hope that you get the idea.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace ConsoleApplicationPlayground
{
class Program
{
static void Main(string[] args)
{
while (true)
{
Int64 phav = PerformanceInfo.GetPhysicalAvailableMemoryInMiB();
Int64 tot = PerformanceInfo.GetTotalMemoryInMiB();
decimal percentFree = ((decimal)phav / (decimal)tot) * 100;
decimal percentOccupied = 100 - percentFree;
Console.WriteLine("Available Physical Memory (MiB) " + phav.ToString());
Console.WriteLine("Total Memory (MiB) " + tot.ToString());
Console.WriteLine("Free (%) " + percentFree.ToString());
Console.WriteLine("Occupied (%) " + percentOccupied.ToString());
Console.ReadLine();
}
}
}

public static class PerformanceInfo
{
[DllImport("psapi.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetPerformanceInfo([Out] out PerformanceInformation PerformanceInformation, [In] int Size);

[StructLayout(LayoutKind.Sequential)]
public struct PerformanceInformation
{
public int Size;
public IntPtr CommitTotal;
public IntPtr CommitLimit;
public IntPtr CommitPeak;
public IntPtr PhysicalTotal;
public IntPtr PhysicalAvailable;
public IntPtr SystemCache;
public IntPtr KernelTotal;
public IntPtr KernelPaged;
public IntPtr KernelNonPaged;
public IntPtr PageSize;
public int HandlesCount;
public int ProcessCount;
public int ThreadCount;
}

public static Int64 GetPhysicalAvailableMemoryInMiB()
{
PerformanceInformation pi = new PerformanceInformation();
if (GetPerformanceInfo(out pi, Marshal.SizeOf(pi)))
{
return Convert.ToInt64((pi.PhysicalAvailable.ToInt64() * pi.PageSize.ToInt64() / 1048576));
}
else
{
return -1;
}

}

public static Int64 GetTotalMemoryInMiB()
{
PerformanceInformation pi = new PerformanceInformation();
if (GetPerformanceInfo(out pi, Marshal.SizeOf(pi)))
{
return Convert.ToInt64((pi.PhysicalTotal.ToInt64() * pi.PageSize.ToInt64() / 1048576));
}
else
{
return -1;
}

}
}
}

How to get application memory usage as shown in Task Manager?

Presumably you're looking at the wrong column in "Task manager" or using the wrong property in Process class..

I guess you're looking for WorkingSet64 not PrivateMemorySize64. PrivateMemorySize64 is the amount of virtual memory allocated for the process, not the physical memory. For physical memory use WorkingSet64.

Also, you need to call process.Refresh() before accessing any of the dynamic properties in process class as it is heavily cached.

process.Refresh();
_data.MemoryUsed = (process.WorkingSet64).ConvertBytesToMegabytes().ToString(CultureInfo.InvariantCulture);


Related Topics



Leave a reply



Submit