Reputation: 560
I am looking for away to get the current amount physical memory used in MB. Something like in the Task Manager
I am current using PerformanceCounter("Memory", "Available MBytes", true);
but its also including the page files (I believe) which is not what I want. Also I want the option of getting the used and not the available memory.
The application I am working on, will monitor the physical memory usage, until the desired threshold is reached. Then it will restart a few windows services.
If you curious as to why I am developing such a program. Some of our programs have memory leaks on the servers, and a we have to restart windows services to release the memory, until we sort out all the memory leaks, I am making this application to help keep the server going, and responsive.
Upvotes: 5
Views: 17287
Reputation: 16718
Using PerformanceCounter class, you can get PF Usage details:
PerformanceCounter pageCounter = new PerformanceCounter
("Paging File", "% Usage", "_Total", machineName);
You can find all the categories information here, Process Object.
ADDED, you can also get Available Memory details using PerformanceCounter
:
PerformanceCounter ramCounter = PerformanceCounter
("Memory", "Available MBytes", String.Empty, machineName);
Using PerformanceCounter
, NextValue()
method you can get the available memory value in MB
, later you can compare it with the threshold value to stop the desired Windows Services.
if (ramCounter.NextValue() > thresholdValue)
{
// ... Stop Desired Services
}
Reference: A Simple Performance Counter Application
Upvotes: 6
Reputation: 29668
Personally I would use with Win32 API GlobalMemoryStatusEx
call through P/Invoke.
You can find out more details here:- http://www.pinvoke.net/default.aspx/kernel32.globalmemorystatusex
Upvotes: 2
Reputation: 15935
If you don't mind calling out to a kernel function. The c++ code to do it is:
MEMORYSTATUSEX statex;
statex.dwLength = sizeof (statex);
GlobalMemoryStatusEx (&statex);
On codeproject you can find out how to call a kernel function from c#:
http://www.codeproject.com/Articles/1285/Calling-API-functions-using-C
Upvotes: 3