How to measure the total memory consumption of the current process programmatically in .NET?

C#.NetPerformanceMemoryMemory Management

C# Problem Overview


How to measure the total memory consumption of the current process programmatically in .NET?

C# Solutions


Solution 1 - C#

Refer to this SO question

Further try this

Process currentProcess = System.Diagnostics.Process.GetCurrentProcess();
long totalBytesOfMemoryUsed = currentProcess.WorkingSet64;

Solution 2 - C#

If you only want to measure the increase in say, virtual memory usage, caused by some distinct operations you can use the following pattern:-

GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();

var before = System.Diagnostics.Process.GetCurrentProcess().VirtualMemorySize64;

// performs operations here

var after = System.Diagnostics.Process.GetCurrentProcess().VirtualMemorySize64;

This is, of course, assuming that your application in not performing operations on other threads whilst the above operations are running.

You can replace VirtualMemorySize64 with whatever other metric you are interested in. Have a look at the System.Diagnostics.Process type to see what is available.

Solution 3 - C#

Solution 4 - C#

I have found this very useful:

Thread.MemoryBarrier();
var initialMemory = System.GC.GetTotalMemory(true);
// body
var somethingThatConsumesMemory = Enumerable.Range(0, 100000)
    .ToArray();
// end
Thread.MemoryBarrier();
var finalMemory = System.GC.GetTotalMemory(true);
var consumption = finalMemory - initialMemory;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJader DiasView Question on Stackoverflow
Solution 1 - C#HotTesterView Answer on Stackoverflow
Solution 2 - C#Adam RalphView Answer on Stackoverflow
Solution 3 - C#Kris KrauseView Answer on Stackoverflow
Solution 4 - C#Jader DiasView Answer on Stackoverflow