PROWAREtech

articles » current » dot-net » kill-or-end-process

.NET: Kill or End a Process

How to terminate a process using C#.

Kill an existing process in .NET with a simple Process.Kill(). There is an optional parameter, true or false, to end all the child processes associated with the process being ended.

Learn how to create processes.

To end the current process:

System.Diagnostics.Process.GetCurrentProcess().Kill(true);

To end all processes with the name "notepad" on the current machine:

static void KillAllNotepadProcesses()
{
	System.Diagnostics.Process[] procs = System.Diagnostics.Process.GetProcessesByName("notepad", "."); // use "." for this machine
	foreach (var proc in procs)
		proc.Kill(true);
}

To end all processes with the name "notepad" on another machine:

static void KillAllNotepadProcesses()
{
	System.Diagnostics.Process[] procs = System.Diagnostics.Process.GetProcessesByName("notepad", "Machine-Name-or-IP-Address"); // enter the IP address or machine name
	foreach (var proc in procs)
		proc.Kill(true);
}

To end all the other instances of the current process:

static void KillAllOtherInstances()
{
	System.Diagnostics.Process thisProc = System.Diagnostics.Process.GetCurrentProcess();
	System.Diagnostics.Process[] procs = System.Diagnostics.Process.GetProcessesByName(thisProc.ProcessName, "."); // use "." for this machine
	foreach (var proc in procs)
		if (proc.Id != thisProc.Id) // the process Id is unique across all processes while the process name can be common
			proc.Kill(true);
}

Complete Real World Example

To expand on the above snippets, the below code has been prepared. It uses brute force to solve π which is very taxing on the CPU. So what happens is it ends (kills) all other instances of itself to prevent over-taxing the machine. Compile this code and try to run more than one instance!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace KillOtherInstancesAndSolvePI
{
	class JobTask
	{
		public Task task { get; }
		public int id { get; }
		public double pi { get; set; }
		public ulong iterations { get; set; }
		public CancellationTokenSource CancelToken { get; }
		public JobTask(int id)
		{
			this.id = id;
			CancelToken = new CancellationTokenSource();
			task = Task.Run(async () => // async not necessary in this example
			{
				var spaces = Environment.ProcessorCount.ToString().Length;
				iterations = (ulong)new Random().Next() * 10;
				Console.WriteLine("Started Job: {0, -" + spaces + "} Iterations: {1}", id, iterations);
				pi = SolvePi(iterations, CancelToken);
				Console.WriteLine("Job: {0, -" + spaces + "} ended with pi={1}", id, pi.ToString("0.00000000000000"));
			}, CancelToken.Token);
		}
		static double SolvePi(ulong count, CancellationTokenSource cancel)
		{
			//π = 3.14159265358979323846264338327950288419...
			//π = (4/1) - (4/3) + (4/5) - (4/7) + (4/9) - (4/11) + (4/13) - (4/15) + ...
			//π = 4 * (1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + 1/13 - 1/15 + ...)

			double x = 1.0;
			for (ulong i = 2; !cancel.IsCancellationRequested & (i < count); i++)
			{
				if ((i & 1) == 0)
					x -= 1.0 / ((i << 1) - 1);
				else
					x += 1.0 / ((i << 1) - 1);
			}
			return 4.0 * x;
		}
	}
	class Program
	{
		static void KillAllOtherInstances()
		{
			System.Diagnostics.Process thisProc = System.Diagnostics.Process.GetCurrentProcess();
			System.Diagnostics.Process[] procs = System.Diagnostics.Process.GetProcessesByName(thisProc.ProcessName, ".");
			foreach (var proc in procs)
				if (proc.Id != thisProc.Id)
					proc.Kill(true);
		}

		static void Main(string[] args)
		{
			KillAllOtherInstances(); // end the other process before trying to solve PI

			var jobTasks = new List<JobTask>();
			Console.WriteLine("pi={0}", 3.1415926535897932384626433833.ToString("0.00000000000000"));
			Console.WriteLine("Logical Processors: {0}", Environment.ProcessorCount);
			Console.WriteLine("ENTER JOB NUMBER TO TERMINATE AT ANYTIME");

			var spaces = Environment.ProcessorCount.ToString().Length;

			int[] jobsIds = new int[Environment.ProcessorCount];
			for (int i = 0; i < Environment.ProcessorCount; i++)
				jobsIds[i] = i;

			foreach(var jobId in jobsIds)
				jobTasks.Add(new JobTask(jobId));

			Thread.Sleep(250);
			foreach (var j in jobTasks.OrderBy(j => j.iterations))
				Console.WriteLine("Job: {0, -" + spaces + "} Iterations: {1}", j.id, j.iterations);

			Task.Run(() => // create a task to terminate the app when all pi tasks are done
			{
				while (jobTasks.Where(j => j.task.IsCompleted == false).Count() > 0)
					Thread.Sleep(250);
				Environment.Exit(0);
			});

			while (jobTasks.Where(j => j.task.IsCompleted == false).Count() > 0) // look for a request to cancel a job from the user
			{
				var id = Console.ReadLine();
				JobTask jt = jobTasks.Where(j => j.id.ToString() == id).FirstOrDefault();
				if(jt != null)
					jt.CancelToken.Cancel();
			}
		}
	}
}

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
CLOSE