Finish a process programmatically

Asked

Viewed 3,387 times

4

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

  • 2

    Does this suit you? https://msdn.microsoft.com/pt-br/library/system.diagnostics.process.kill(v=vs.110). aspx

2 answers

5

If you want to finish 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) return a array of strings with all cases whose name contains string passed to the method. Then, just iterate through the found processes and invoke the method .Kill().

You can also finish the process by ID as follows:

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

The method .Kill() force the application to be completed. However, bear in mind that the method is asynchronous, that is, it is sent the signal to finish the process, but the return of the method does not mean that the process has ended.

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 .WaitForExit() blocks the execution of your program until the process is finished.

The downside is that your program can be stopped indefinitely.

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

So, to confirm that the process went out correctly, check the value of p.HasExited.

1

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.