简体   繁体   English

c#中如何管理多个进程

[英]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.所以基本上我的主进程将一直运行并观察进程 1 或 2 是否退出,如果是则重新启动它们。

With following code the program just exits right away with 0 errors.使用以下代码,程序会立即退出,出现 0 个错误。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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