Close a recently opened process C#

Question:

I need to execute a process for a certain time, for which I start a process, and through a Timer after 10 minutes, I kill it using Kill() , I do it as follows:

using System.Diagnostics;
using System.Threading;
public class Manager{
    private Process Proceso;

    public Manager(){        
        //Inicio el proceso EdmServer
        Proceso = Process.Start(@"C:\Program Files\SOLIDWORKS PDM\EdmServer.exe");
        //StopProcess se ejecuta tras 10 minutos.
        Timer t = new Timer(StopProcess, null, 600000 , 0);
    }

    private void StopProcess(object o)
    {
        try
        {             
            Proceso.Kill();
        }    
        catch(Exception ex)
        {
            ex.CreateLog();
        }
        finally
        { 
            Environment.Exit(0);
        }
    }
}

The code works as I expect, the thing is that by raising the time I intend to keep the process open, increasing the Timer wait, when closing the process, the following exception is generated:

The request cannot be processed because the process has ended.

The thing is, that it goes through the finally , the execution ends, but the process that I intend to close is still open.

Why is the exception thrown if the process did NOT finish?

Answer:

As I see in the code provided in your question, you are not specifying which process to terminate.

To terminate the process correctly you can use the following code:

Process [] proc Process.GetProcessesByName("EdmServer.exe");
proc[0].Kill();

Modified code from: How to terminate a process in c# – social.msdn.microsoft.com

It is also worth taking into account the information available in the official documentation :

  • The "Kill" method is executed asynchronously. After calling the "Kill" method, call the WaitForExit method to wait for the process to exit, or check the HasExited property to determine if the process has exited.
  • NotSupportedException : Raised when calling the Kill() method for a process running on a remote computer. The Kill() method is only available to processes running on the local computer.
  • If the call to the Kill method is made while the process is terminating, the Win32Exception exception is thrown indicating (Access Denied).
Scroll to Top