The Trick is I also need to be able to do it on multi core machines. My education in C# is a tad broken. I have managed the following code. Can anyone help me out? Iv tried
You can only read the performance counters every 100 ms or the timesilce will be too small for it to get a accurate reading, if you read more than once every 100ms it will always report 0 or 100% usage. Because you call NextValue()
twice (once for the file, once for your stream) the second reading will be the usage since the previous reading the line before.
Change your code to this:
foreach (Process process in runningNow.Where(x => x.ProcessName == procName)
{
using (PerformanceCounter pcProcess = new PerformanceCounter("Process", "% Processor Time", process.ProcessName))
using (PerformanceCounter memProcess = new PerformanceCounter("Memory", "Available MBytes"))
{
pcProcess.NextValue();
Thread.Sleep(60000);
StreamWriter OurStream;
OurStream = File.AppendText("c:\\CPUMON.txt");
Console.WriteLine("");
OurStream.WriteLine("");
Console.ForegroundColor = ConsoleColor.Red;
float cpuUseage = pcProcess.NextValue();
Console.WriteLine("Process: '{0}' CPU Usage: {1}%", process.ProcessName, cpuUseage);
OurStream.WriteLine("Process: '{0}' CPU Usage: {1}%", process.ProcessName, cpuUseage);
Console.ForegroundColor = ConsoleColor.Green;
float memUseage = memProcess.NextValue();
Console.WriteLine("Process: '{0}' RAM Free: {1}MB", process.ProcessName, memUseage);
OurStream.WriteLine("Process: '{0}' RAM Free: {1}MB", process.ProcessName, memUseage);
}
}
There may be other issues causing you problems but calling NextValue twice is the first one that jumped out at me.
Explanation:
The reason behind NextValue
only reporting 0 or 100% when you request NextValue
too fast is the fact that if you are currently executing code or not is a boolean factor.
So what the performance counter is doing is asking the question:
Between the last time the performance counter took a reading and right now, what % of time slices had code executing from the process X?
The size of those time slices the performance counter works with is 100ms so if you go below 100ms you are basically asking
Did the last time slice that was recorded by the performance counter have code from the process X executing?
and the only two answers you can get to that question are "No" (0%) or "Yes" (100%).