1

I have a console app that I need to manage multiple processes. By manage i mean that if one process exits that i want to start it up again. So basically my main process will run all the time and watch to see if process 1 or 2 exits and if so to start them again.

With following code the program just exits right away with 0 errors.

static void Main() {
    Task.Run(() => Process1());
    Task.Run(() => Process2());
}

private static void Process1() {
    ProcessStartInfo startInfo = new ProcessStartInfo();
    startInfo.CreateNoWindow = false;
    startInfo.UseShellExecute = false;
    startInfo.FileName = "a process 1 file path";
    startInfo.WindowStyle = ProcessWindowStyle.Minimized;
    try {
        using (Process exeProcess = Process.Start(startInfo)) {
            exeProcess.WaitForExit();
        }
        Process1();
    }
    catch (Exception ex) {
        Console.WriteLine(ex.Message);
    }
}

private static void Process2() {
    ProcessStartInfo startInfo = new ProcessStartInfo();
    startInfo.CreateNoWindow = false;
    startInfo.UseShellExecute = false;
    startInfo.FileName = "a process2 file path";
    startInfo.WindowStyle = ProcessWindowStyle.Minimized;
    try {
        using (Process exeProcess = Process.Start(startInfo)) {
            exeProcess.WaitForExit();
        }
        Process2();
    }
    catch (Exception ex) {
        Console.WriteLine(ex.Message);
    }
}
Maxqueue
  • 2,194
  • 2
  • 23
  • 55
  • What's the problem with the code that you've posted? – Theodor Zoulias Dec 20 '21 at 03:14
  • @Theodor Zoulias It just exits main program immediately – Maxqueue Dec 20 '21 at 03:25
  • You could pinvoke and create them using windows jobs to do this, [example](https://stackoverflow.com/questions/6266820/working-example-of-createjobobject-setinformationjobobject-pinvoke-in-net) – nna12 Dec 20 '21 at 03:26
  • @nna12 I feel like i should be able to do it similarly to the way i have in my example. I am just missing something basic. – Maxqueue Dec 20 '21 at 03:29
  • 1
    Why not just use something to wrap your exes up as devices then get the windows device manager to watch them and restart them. If you have the code for the exes you're going to watch, upgrade them to be services – Caius Jard Dec 20 '21 at 04:07
  • @Caius Jard Services would have worked great. Not sure why i didn't think of that but i found a solution. Putting together answer now. – Maxqueue Dec 20 '21 at 04:29
  • Sorry, "devices" there (twice) was a typo of services - well done on decoding what my fat thumbs on a tiny iPhone keyboard meant there! – Caius Jard Dec 20 '21 at 05:03

1 Answers1

2

I was able to solve this by removing the recursive calls, putting each method that managed a task into a infinite loop and then awaiting each task:

static void Main() {
    var task1 = Task.Run(() => Process1());
    var task2 = Task.Run(() => Process2());
    Task.WaitAll(task1, task2);
}
Maxqueue
  • 2,194
  • 2
  • 23
  • 55