C# Process.GetProcessesByName

Process illustration

You want to see an example of the Process.GetProcessesByName method from the System.Diagnostics namespace in the C# language. Though this functionality can be derived by using other methods such as GetProcesses, this method is also useful.

Process.GetProcesses Method

Example

Here we use Process.GetProcessesByName in a while true loop. We use the argument "chrome" to GetProcessesByName; this returns an array of all processes with name "chrome". Then, we sleep for five seconds before calling the method again.

While Loop Examples Sleep Method Pauses Programs

This C# example demonstrates the Process.GetProcessesByName method.

Program that uses Process.GetProcessesByName [C#]

using System;
using System.Diagnostics;
using System.Threading;

class Program
{
    static void Main()
    {
	while (true)
	{
	    // Omit the exe part.
	    Process[] chromes = Process.GetProcessesByName("chrome");
	    Console.WriteLine("{0} chrome processes", chromes.Length);
	    Thread.Sleep(5000);
	}
    }
}

Output

0 chrome processes
3 chrome processes
4 chrome processes
5 chrome processes
5 chrome processes
5 chrome processes

Explanation. During the execution of this program, I opened the Chrome web browser and opened several tabs. You can see that Chrome created up to five processes during this. Because of its multi-process model, Chrome can run in several processes at once and this changes during normal usage.

Warning

Avoid exe. The method did not work when I tried using the string "chrome.exe" as the argument. The name does not include the file extension.

Summary

We looked at how the Process.GetProcessesByName method can be used to get an array of all Process instances for a certain name. For a process that may have many instances running, this method can isolate them and make for a convenient way to analyze its resource usage.

.NET Framework Info
.NET