BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

System Information
.NET 1.1+

Terminating Processes

Sometimes it is necessary to terminate a process immediately, or request that an application close normally, possibly with user intervention. Both actions are possible using methods of the Process class.

Kill

In an earlier article I explained how you can retrieve a list of all of the running processes on the local machine and how you can detect if one of those processes has stopped responding. If you do detect such an item, or if you are writing a program that monitors processes, you might want to terminate a process programmatically.

One way in which you can terminate a process is using the Process class's Kill method. This attempts to immediately stop the process and release its resources. You should use the method with care; as the program's normal closing actions will not run, any unsaved data could be lost.

You can only use the Kill method to stop local processes; calling it for a remote process results in an exception being thrown. You will also generate an exception if you try to kill processes that have already exited, or certain system processes. The latter reduces the risk of stopping a process that is required for the operating system's stability.

process.Kill()

NB: The Kill method executes asynchronously. If you need to determine that the process has terminated, either wait for it to close by calling WaitForExit, or check the value of the HasExited property.

CloseMainWindow

A less dangerous alternative to killing processes is to request that they close by calling their CloseMainWindow method. This gives the same result as the user closing an application's main window manually. If the program would normally require confirmation from the user, perhaps asking if a modified document should be saved, this confirmation will be requested.

Although safer, CloseMainWindow is not always available. You can only call the method successfully for processes that include a user interface. If the process has stopped responding, it will not terminate immediately, as it would with the Kill method.

You can determine whether the method succeeded by checking the Boolean return value. If true, a message was sent to the application's main window. However, this does not mean that the application was actually closed. You must still use either WaitForExit or HasExited to ensure that the process terminated.

bool messageSent = process.CloseMainWindow()

Example

To demonstrate programmatic termination of processes, try adding the code below to a console application. This program lists all of the currently running processes and allows you to terminate one by entering its process ID. Pressing Enter without typing an ID exits the program. Note the use of try/catch blocks to detect problems when trying to locate or kill a process.

NB: You can download the sample program using the link at the start of this article.

static void Main(string[] args)
{
    string input = null;

    while (input != "")
    {
        ListProcesses();
        ShowInstructions();
        input = Console.ReadLine();
        ProcessInput(input);
    }
}

static void ShowInstructions()
{
    Console.ForegroundColor = ConsoleColor.White;
    Console.WriteLine("Enter a process ID to kill it or press Enter to stop");
}

static void ListProcesses()
{
    Console.ForegroundColor = ConsoleColor.Magenta;
    Process[] processes = Process.GetProcesses();
    foreach (Process process in processes)
    {
        Console.WriteLine("{0}: {1}", process.Id, process.ProcessName);
    }
}

static void ProcessInput(string input)
{
    int processId;

    if (int.TryParse(input, out processId))
    {
        KillProcessIfPresent(processId);
    }
    else if (input.Length != 0)
    {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine("Invalid input");
    }
}

static void KillProcessIfPresent(int processId)
{
    try
    {
        Process toKill = Process.GetProcessById(processId);
        KillProcess(toKill);
    }
    catch
    {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine("Process not found");
    }
}

static void KillProcess(Process toKill)
{
    try
    {
        toKill.Kill();
        Console.ForegroundColor = ConsoleColor.Green;
        Console.WriteLine("Process {0} killed", toKill.Id);
    }
    catch (Exception ex)
    {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine("Unable to kill process {0}", toKill.Id);
        Console.WriteLine(ex.Message);
    }
}
13 March 2016