Using System;
Using System.Collections.Generic;
Using System.Diagnostics;
Using System.Linq;
Using System.Management;
Using System.Text;
Using System.Threading;
Using System.Threading.Tasks;
Namespace Process Monitoring
{
Class Program
{
static void Main (string[] args)
{
Process[] processes = Process.getprocessesbyname ("taskmgr");
foreach (Process instance in processes)
{
Console.WriteLine ("");
Console.WriteLine ("ProcessName:" + instance. ProcessName);
Try
{
Console.WriteLine ("Commit size \ t" + instance. pagedmemorysize64/1024);
Console.WriteLine ("Working setup (memory) \ t" + instance. workingset64/1024);
Console.WriteLine ("Number of threads \ t" + instance. Threads.count);
Console.WriteLine ("Number of handles \ t" + instance. Handlecount);
}
Catch {}
}
Process p = processes[1];
PerformanceCounter ramcounter = new PerformanceCounter ("Process", "Working Set", p.processname);
PerformanceCounter cpucounter = new PerformanceCounter ("Process", "% Processor time", p.processname);
var objquery = new ObjectQuery ("SELECT * from Win32_Process WHERE ProcessID =" + p.id);
var mosearcher = new ManagementObjectSearcher (objquery);
DateTime firstsample = datetime.minvalue, secondsample = Datetime.minvalue;
Double processorusage;
Double mspassed;
ULONG u_oldcpu = 0;
while (true)
{
var gets = Mosearcher.get ();
foreach (ManagementObject mobj in gets)
{
Try
{
if (firstsample = = Datetime.minvalue)
{
Firstsample = DateTime.Now;
Mobj.get ();
U_OLDCPU = (ULONG) mobj["Usermodetime"] + (ULONG) mobj["Kernelmodetime"];
}
Else
{
Secondsample = DateTime.Now;
Mobj.get ();
ULONG U_NEWCPU = (ULONG) mobj["Usermodetime"] + (ULONG) mobj["Kernelmodetime"];
mspassed = (secondsample-firstsample). TotalMilliseconds;
Processorusage = (U_NEWCPU-U_OLDCPU)/(mspassed * 100.0 * environment.processorcount);
U_OLDCPU = U_NEWCPU;
Firstsample = Secondsample;
Console.WriteLine ("Processorusage:" + (int) processorusage);
}
}
catch (Exception ex)
{
Console.WriteLine (ex. Message + ex. StackTrace);
Console.WriteLine (ex. Innerexception.message);
}
}
Thread.Sleep (1000);
}
Console.ReadLine ();
}
}
}
C # gets CPU usage for a process (similar to display CPU in Task Manager)