监控过程始终在运行

时间:2014-03-25 14:45:14

标签: c# monitoring

有人知道如何在C#中创建一个Monitor程序来控制应用程序将始终运行吗?我需要它是一个双监视器应用程序,我将解释:我有一个应用程序Ap1必须控制它始终启动的Ap2进程,并且Ap2必须控制它始终启动的Ap1进程。在恢复中,如果我杀死Ap1进程,Ap2应用程序应立即启动Ap1(反之亦然,如果Ap2死亡)。

这个我正在开发但没有工作的代码,我不知道,但是当我杀死监控的程序时,没有重新开始。

        public void Monitor()
        {
            Console.WriteLine("Monitoring {0} process...", processname);

            while (IsProcessRunning() == true)
            {
                Process[] runningNow = Process.GetProcesses();

                foreach (Process process in runningNow)
                {
                    if (process.ProcessName == processname)
                    {
                        System.Threading.Thread.Sleep(1000);
                        Console.WriteLine("Process:{0} is running actually", process.ProcessName);
                    }
                    else { /* Provide a messagebox. */ }
                }

                // Sleep till the next loop
                Thread.Sleep(intInterval);
            }



            while (IsProcessRunning() != true)
            {
                ProcessMonitor proc = new ProcessMonitor("ConsoleApplication1", 1000);//Check if is running each 1 second
                Console.WriteLine("Process:{0} is NOT running actually", processname);
                //Application folder of exe
                String applicationFolder = "C:\\App";

                //Get the executable file
                String procPath = applicationFolder + @"\Ap1.exe";

                Console.WriteLine("Running {0} process...", proc.Name);
                //Lauch process
                Process p = Process.Start(procPath);
                Console.WriteLine("Process running {0} OK", proc.Name);
                //p.WaitForExit(10000);
            }
        }

主程序:

static void Main(string[] args)
    {
        ProcessMonitor proc = new ProcessMonitor("ConsoleApplication1", 1000);//Check if is running each 1 second
        if (proc.IsProcessRunning() != true)
        {
            Console.WriteLine("{0} is not running.", proc.Name);

            //Application folder of exe
            String applicationFolder = "C:\\App";

            //Get the executable file
            String procPath = applicationFolder + @"\Ap1.exe";

            Console.WriteLine("Running {0} process...", proc.Name);
            //Lauch process
            Process p = Process.Start(procPath);
            Console.WriteLine("Process running {0} OK", proc.Name);
            //p.WaitForExit(10000);
        }
        else
        {
            proc.Monitor();
        }

        proc.FreezeOnScreen(); 
    }

2 个答案:

答案 0 :(得分:0)

您可以在任务计划程序中设置一个任务,该任务以设定的间隔(例如每半小时)启动您的程序。我相信如果已经有一个实例在运行,你可以将它设置为不启动任务。 (如果我错了,请纠正我)

答案 1 :(得分:0)

我们需要这一次,并且只是定期监视进程列表,检查进程的名称。如果该过程在给定的时间内不存在,我们重新启动它。您可以使用Process.GetProcessesByName