Get the program’s memory usage in C#

[memory usage]


This example uses the following code to display information about its memory usage.

// Display information about the current process's memory usage.
private void Form1_Load(object sender, EventArgs e)
{
    Process proc = Process.GetCurrentProcess();
    AddItem(lvMemory, "Min Working Set",
        ((double)proc.MinWorkingSet).ToFileSize());
    AddItem(lvMemory, "Max Working Set",
        ((double)proc.MaxWorkingSet).ToFileSize());
    AddItem(lvMemory, "Non-paged Memory Size",
        ((double)proc.NonpagedSystemMemorySize64).ToFileSize());
    AddItem(lvMemory, "Paged Memory Size",
        ((double)proc.PagedMemorySize64).ToFileSize());
    AddItem(lvMemory, "Paged System Memory Size",
        ((double)proc.PagedSystemMemorySize64).ToFileSize());
    AddItem(lvMemory, "Peak Paged Memory Size",
        ((double)proc.PeakPagedMemorySize64).ToFileSize());
    AddItem(lvMemory, "Peak Virtual Memory Size",
        ((double)proc.PeakVirtualMemorySize64).ToFileSize());
    AddItem(lvMemory, "Peak Working Set",
        ((double)proc.PeakWorkingSet64).ToFileSize());
    AddItem(lvMemory, "Virtual Memory Size",
        ((double)proc.VirtualMemorySize64).ToFileSize());
    AddItem(lvMemory, "Working Set",
        ((double)proc.WorkingSet64).ToFileSize());

    lvMemory.Columns[0].AutoResize(
        ColumnHeaderAutoResizeStyle.ColumnContent);
    lvMemory.Columns[1].AutoResize(
        ColumnHeaderAutoResizeStyle.ColumnContent);
}

The code get the program’s Process object and then uses its properties to learn about its memory usage.

The AddItem method simply adds a new item and subitems to the lvMemory ListView control. The ToFileSize extension method converts a memory size in bytes into a more useful unit such as KB or MB. Download the example and look at the code to see the details.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in memory, programs and tagged , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *