C#进程重启循环 [英] C# process restart loop
问题描述
我正在尝试制作一个控制台应用程序,它可以监控某个进程并在它退出时重新启动它.因此,控制台应用程序始终处于开启状态,唯一的工作就是重新启动其他一些进程.
I'm trying to make a console app that would monitor some process and restart it if it exits. So, the console app is always on, it's only job is to restart some other process.
我在下面发布了我的代码......它基本上可以工作,但只是为了一个进程重启......
I posted my code below.. it basically works but just for one process restart...
我将不胜感激!
提前致谢!
{
System.Diagnostics.Process[] p = System.Diagnostics.Process.GetProcessesByName(SOME_PROCESS);
p[0].Exited += new EventHandler(Startup_Exited);
while (!p[0].HasExited)
{
p[0].WaitForExit();
}
//Application.Run();
}
private static void Startup_Exited(object sender, EventArgs e)
{
System.Diagnostics.Process.Start(AGAIN_THAT_SAME_PROCESS);
}
推荐答案
你需要一个循环,在循环的顶部你需要重新启动程序后将 p
重新附加到新的进程.所以就像:
You need a loop, and at the top of the loop you need to reattach p
to the new process after restarting the program. So something like:
Process p = /* get the current instance of the program */;
while (true)
{
p.WaitForExit();
p = Process.Start(/* the program */);
}
请注意,由于 Process.Start 返回新实例的 Process 对象,您实际上不需要重新执行搜索:您可以直接等待新的 Process 对象.
Note that since Process.Start returns the Process object for the new instance, you don't actually need to re-perform the search: you can just wait directly on the new Process object.
这篇关于C#进程重启循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!