17. April 2008 00:48
This is a simple way in .NET 2.0 to monitor processes on your machine or a remote machine. This example also monitors how much cpu usage the process is using at the time of monitoring. Keep in mind this example also kills the process if it goes over 10% CPU Usage.
private static void killProcess()
{
Console.WriteLine("Watching to Kill Process!");
int intInterval = 1000; // 1 second
string procName = "YourProcessName";
while (true)
{
Process[] runningNow = Process.GetProcesses();
foreach (Process process in runningNow)
{
using (PerformanceCounter pcProcess = new PerformanceCounter("Process", "% Processor Time", process.ProcessName))
{
if (process.ProcessName == procName)
{
pcProcess.NextValue();
System.Threading.Thread.Sleep(1000);
Console.WriteLine("Process:{0} CPU% {1}", process.ProcessName, pcProcess.NextValue());
if(pcProcess.NextValue() > float.Parse("10"))
{
Console.WriteLine(string.Format("Killing {0} at {1}", procName, DateTime.Now.ToString()));
process.Kill();
}
}
}
}
// Sleep till the next loop
Thread.Sleep(intInterval);
}
}
Make sure you reference the following:
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Threading;
using System.Collections;
Anyway this is cool if you are needing to send alerts if a program takes up too much CPU usage or whatever the case may be. Also .GetProcesses() and PerformanceCounter() have overloads that except the remote computer name.
9bfe8577-5549-459b-8f46-8a98fe93b9fc|1|5.0
Tags: c#
C#