Terminate a process programmatically

4

I want to make a program that presents a Task Manager to the user. I already have the remaining logic, but how can I end a process ( task kill ) with C# ?

    
asked by anonymous 22.04.2015 / 20:56

2 answers

4

If you want to terminate a set of processes that share the same name:

var processes = Process.GetProcessesByName(string);
foreach(var p in processes)
    p.Kill();

The method .GetProcessesByName(string) returns a array of% with% of all processes whose name contains the strings passed to the method. Then, iterate through the processes found and invoke the method string .

You can also terminate the process by ID as follows:

Process p = Process.GetProcessById(int);
p.Kill();

The .Kill() method forces the application to terminate. However, note that the method is asynchronous, that is, the sign is sent to the process, but the return of the method does not mean that the process is finished.

To wait for the end of the process, do the following:

Process p = Process.GetProcessById(int);
p.Kill();
p.WaitForExit(); // bloqueia a execução ate que o processo termine

The method .Kill() blocks the execution of your program until the process is finished.

The downside is that your program may be idle for an indefinite period of time.

To avoid this situation you can still pass an integer to .WaitForExit() . This integer will be the time, in milliseconds, waited for the process to end. If time passes without the process terminating, the method returns.

So, to confirm that the process exited correctly, check the value of .WaitForExit(int) .

    
22.04.2015 / 21:40
1

The following code ends the process with PID 9812, for example:

Process p = Process.GetProcessById(9812);
p.Kill();
    
22.04.2015 / 21:35