Close a recently opened process C #

4

I need to perform the execution of a process for a certain time, for which I start a process, and using a Timer after 10 minutes, I kill it using Kill() , I do it in the following way:

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 hope, the issue is that by raising the time I intend to keep the process open, increasing the wait of Timer , when closing the process, the following exception is generated:

  

The request can not be processed because the process has finished.

The issue is, that goes through the finally , the execution finishes, but the process that I intend to close is still open.

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

    
asked by Juan Salvador Portugal 04.01.2019 в 13:02
source

1 answer

4

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

To finish 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 at official documentation :

  • The "Kill" method runs asynchronously. After calling the "Kill" method, call the method WaitForExit to wait for the process to exit, or check the HasExited to determine if the process has come out.
  • NotSupportedException : Generated by calling the Kill() method for a process that is running on a remote computer. The Kill() method is only available for processes running on the local computer.
  • If the call to the Kill method is made while the process is ending, the exception Win32Exception is launched indicating (Access Denied).
answered by 04.01.2019 / 15:37
source