Wednesday 6 January 2010

System Resources Monitor C#

As a continuation to the last program that monitor network stat, i created another one, now monitoring system resources such as cpu usage and memory usage.
I used PerformanceCounter for the current usage of both, and gotten the installed memory size from the windows management.
Also used threading to speed up and parrellize the proccess of getting the data.

Every 3 seconds:The system check the average cpu usage over the 3 seconds, and memory usage once(memory usage is far less dynamic compared to cpu usage).
Much like the previous example, the form is composed of a single Label named label1

public System.Diagnostics.PerformanceCounter pc=new System.Diagnostics.PerformanceCounter();
void getdata()
{
//using System.Threading;
//using System.Management;
//*IMPORTANT*also! you must add the management to the referances!!!!
System.Diagnostics.PerformanceCounter ram = new System.Diagnostics.PerformanceCounter("Memory", "Available MBytes");

label1.Text="";

int mem=0;

//check main memory size, it wont change during the running, thus only ran once.
ObjectQuery winQuery = new ObjectQuery("Select * from Win32_ComputerSystem");

ManagementObjectSearcher searcher = new ManagementObjectSearcher(winQuery);

foreach (ManagementObject item in searcher.Get())
{
mem=System.Convert.ToInt32(item["TotalPhysicalMemory"])/1024/1024;
}


while (this.Disposing==false)
{
//long tick=DateTime.Now.Ticks; //the ticks can be used to find out how much time each loop takes
Thread th=new Thread(new ThreadStart(setcpurate));
th.Start();
//lets get some more data, like free mem while he works, however, its best to make ones that wont sabotage the data

//to prevent corrupting the cpu data with these calculations, lets sleep while he works.
while (th.ThreadState==ThreadState.Running) Thread.Sleep(101);
label1.Text+="free memory="+ram.NextValue().ToString()+"MB of ";
label1.Text+=mem+" MB\n";
Application.DoEvents();

while (th.ThreadState!= ThreadState.Stopped) Thread.Sleep(100);
//now the cpu usage thread should be done.
label1.Text+="cpu usage="+str+"\n";
//tick=DateTime.Now.Ticks-tick;
//label1.Text+="time to calculate: "+tick/TimeSpan.TicksPerMillisecond+" ms\n";
Application.DoEvents();
}
}

void setcpurate()
{ //set the cpu rate to str, yea, i know i should have used a semaphor\mutex\we,
//but if you wait till thread is dead, the data is already in place
pc.CategoryName = "Processor";
pc.CounterName = "% Processor Time";
pc.InstanceName = "_Total";
pc.NextValue(); //always return 0 on first run
float activity = 0;
int NormalDegree = 15;
for (int i = 0; i < NormalDegree; i++) //averaging over 3 seconds
{
activity += pc.NextValue();
Application.DoEvents();
Thread.Sleep(200);
}
Thread.MemoryBarrier();
str=(activity/NormalDegree).ToString("g3")+"%";
}

1 comment: