简体   繁体   中英

How to manage multiple processes in c#

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);
    }
}

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM