.NET Tip: It’s 2:00 a.m. Do You Know What Your Processes Are Doing?

I recently needed to check on the status of some processes running on a server. I simply logged into the server and fired up Task Manager. This worked fine for a quick one-time check. What is really needed, though, is an automated way to keep tabs on these processes. The .NET Framework has classes that make it very easy to retrieve the same information that is available on the Processes tab in Task Manager. Here is a function that takes a process and returns its current state:

public enum ProcessState
   Responding,
   NotResponding,
      Unknown
}

public static ProcessState GetProcessState(Process Proc)
{
   if (Proc.MainWindowHandle == IntPtr.Zero)
      return ProcessState.Unknown;
   else if (Proc.Responding)
      return ProcessState.Responding;
   else
      return ProcessState.NotResponding;
}

The function above then can be used to determine the state of all processes running on the server. The following code loops through all processes running on the machine and displays their name and status.

ProcessState State;
foreach (Process Proc in Process.GetProcesses())
{
   State = Util2008.GetProcessState(Proc);
   Debug.Print("{0}: {1}", Proc.ProcessName, State.ToString());
}

Here is the output for the first few processes running on my computer.

OUTLOOK: Responding xplore: Responding
k9filter: Unknown
vpngvpngui: Unknown

You now have everything you need to automate monitoring the processes. Simply check that state of the process on a periodic basis and then take the appropriate action if the state is not what is expected.

About the Author

Jay Miller is a Software Engineer with Electronic Tracking Systems, a company dedicated to robbery prevention, apprehension, and recovery based in Carrollton, Texas. Jay has been working with .NET since the release of the first beta and is co-author of Learn Microsoft Visual Basic.Net In a Weekend. Jay can be reached via email at jmiller@sm-ets.com.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read