I need to execute the execution of a process for a certain time, for which I start a process, and 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 expect, the thing is that by raising the time I intend to keep the process open, increasing the wait for the Timer
, when closing the process, the following exception is generated:
The request cannot be processed because the process has ended.
The thing is, when 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?
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:
It is also worth taking into account the information available in the official documentation :
Kill()
for a process running on a remote computer. The methodKill()
is only available for processes running on the local computer.Kill
is made while the process is terminating, the Win32Exception exception is thrown indicating (Access Denied).To terminate a specific process use the following line of code.