Home > C#

Monitor Processes and CPU Usage

17. April 2008

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.

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

C#

Comments

4/17/2008 7:23:16 AM #
Trackback from DotNetKicks.com

Monitor Process and CPU Usage
12/8/2008 6:53:34 PM #
How shall I modify the code to get a message "The process is over 10% of CPU" instead of killing the process?
John_M
12/8/2008 8:59:49 PM #
Instead of this in the if statement change it to you want

Console.WriteLine(string.Format("Killing {0} at {1}", procName, DateTime.Now.ToString()));
process.Kill();


Could be

Console.WriteLine(string.Format("{0} is over 10% utilization", procName));

Or you could write to a file of some sort like flat file or xml file for logging.

Hope this helps!  

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading