BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

System Information
.NET 2.0+

Getting the Current Application's Memory Usage

When you are creating an application that can be memory-intensive, it may be useful to monitor the current memory usage. This allows you to modify the behaviour of the program as its RAM requirements increase and to predict out-of-memory exceptions.

Monitoring Memory Usage

There are many reasons why you may wish to monitor the memory usage of an application. For example, during normal operation you may wish to display the memory usage to the user or modify the behaviour of a program according to the amount of RAM that it is using. During development and maintenance, you may wish to monitor the memory used to help you to detect possible memory leaks and other bugs in the software.

In this short article we will use the Process class of the .NET framework to obtain the memory usage of the current application.

Obtaining the Memory Usage

The Process class can be found within the System.Diagnostics namespace. To make the code easier to read, add the following using directive at the top of your code file.

using System.Diagnostics;

The first step is to obtain the process for the currently executing program. This is achieved using a static method of the Process class named "GetCurrentProcess". The method requires no parameters.

Process currentProc = Process.GetCurrentProcess();

Once you have a reference to the current process, you can determine its memory usage by reading the PrivateMemorySize64 property. As the name suggests, this returns a 64-bit integer value containing the number of bytes of memory that the process is currently using. The property can be used with 32-bit or 64-bit operating systems and processors.

long memoryUsed = currentProc.PrivateMemorySize64;
27 June 2009