0

Hello so I'm currently developing a program to help me automate the functionality of a python script, after a lot of research I found a way to launch and read the output of the python script to a C# console window but I want to implement a time-based condition for it to stop (close process after 5 minutes for example). My code for opening the process is as followed (credits to the original writer):

 var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = "C:\\Python27\\python.exe",
                    Arguments = cmd,
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    CreateNoWindow = true
                },
                EnableRaisingEvents = true
            };
            process.ErrorDataReceived += Process_OutputDataReceived;
            process.OutputDataReceived += Process_OutputDataReceived;

            process.Start();
            process.BeginErrorReadLine();
            process.BeginOutputReadLine();

            process.WaitForExit();
            Console.Read();

As you can see the process waits for it to be finished but the script can sometimes stall or not function correctly, I would like to add a time based condition to close the process if it's not completed after 5 minutes. I record the time by using the StopWatch class but having trouble targeting the process to close it, 5 different processes of the python script run at once so closing the python process would not be viable. I also use process.WaitForExit(); which waits until the process has finished but like I said above this isn't always the case so it's causing problems with processes never closing.

TL;DR: If process takes longer than 5 minutes to complete -> Force close

Any suggestions please?

Teymour
  • 1,832
  • 1
  • 13
  • 34
James D
  • 341
  • 1
  • 3
  • 13
  • [How do you add a timer to a C# console application](https://stackoverflow.com/q/186084/7444103). BTW, `EnableRaisingEvents` is used to handle the `Exited` event (instead of the sync version, `WaitForExit()`). – Jimi Oct 12 '19 at 13:34
  • I know how to add a timer, I'm asking how I can link it to closing the process after x time has passed. – James D Oct 12 '19 at 14:05
  • 1
    ? Declare your `process` as a Field, call `process.Kill()` when the Timer elapses. `Dispose()` of the process, rinse and repeat for any new process you create. – Jimi Oct 12 '19 at 14:08

0 Answers0