This is what im doing in form1:
void PopulateApplications()
{
DoubleBufferedd(dataGridView1, true);
int rcount = dataGridView1.Rows.Count;
int rcurIndex = 0;
foreach (Process p in Process.GetProcesses())
{
try
{
if (File.Exists(p.MainModule.FileName))
{
memoryUsage = Core.getallmemoryusage(p.ProcessName);
Core.getcpu(p.ProcessName);
cpuusage = Core.processes;
var icon = Icon.ExtractAssociatedIcon(p.MainModule.FileName);
Image ima = icon.ToBitmap();
ima = resizeImage(ima, new Size(25, 25));
ima = (Image)(new Bitmap(ima, new Size(25, 25)));
String status = p.Responding ? "Running" : "Not Responding";
if (rcurIndex < rcount - 1)
{
var currentRow = dataGridView1.Rows[rcurIndex];
currentRow.Cells[0].Value = ima;
currentRow.Cells[1].Value = p.ProcessName;
currentRow.Cells[2].Value = cpuusage;
currentRow.Cells[3].Value = memoryUsage;
currentRow.Cells[4].Value = status;
}
else
{
dataGridView1.Rows.Add(ima, p.ProcessName,cpuusage,memoryUsage, status);//false, ima, p.ProcessName, status);
}
rcurIndex++;
}
}
catch ( Exception e)
{
string t = "error";
}
}
if (rcurIndex < rcount - 1)
{
for (int i = rcurIndex; i < rcount - 1; i++)
{
dataGridView1.Rows.RemoveAt(rcurIndex);
}
}
}
Now the method in form1 PopulateApplications
, I call it from a timer tick event each 5 seconds.
Then I loop each time over the processes and get the memory usage and CPU usage.
This are the methods of memory and CPU in the class Core
.
With the memory method there is no problems. Working good and fast.
public static string getallmemoryusage(string processName)
{
var counter = new PerformanceCounter("Process", "Working Set - Private", processName);
privateMemeory = (counter.NextValue() / 1024 / 1024).ToString();
//string.Format("Private memory: {0}k", counter.NextValue() / 1024 / 1024);
return privateMemeory;
}
The problem is with the getcpu
method. I need to make it sleep every 1000ms few times to get the CPU usage. If I use a breakpoint on this method, I will get the value in the end. The problem is when I call the method in form1 each 5 seconds it's also calling and doing this getcpu
every 5 seconds and those threads sleep make it work very slow. If I will set the threads sleep to 10ms it will be faster but then I get on most processes 0% or 100% usage.
public static string getcpu(string name)
{
var cpuload = new PerformanceCounter("Processor", "% Processor Time", "_Total");
processes = Convert.ToInt32(cpuload.NextValue()) + "%";
System.Threading.Thread.Sleep(1000);
processes = cpuload.NextValue() + "%";
System.Threading.Thread.Sleep(1000);
processes = cpuload.NextValue() + "%";
System.Threading.Thread.Sleep(1000);
processes = cpuload.NextValue() + "%";
System.Threading.Thread.Sleep(1000);
processes = cpuload.NextValue() + "%";
System.Threading.Thread.Sleep(1000);
return processes;
}